From dedc6ecd5b981ad8570183c8ef502d4bc3d83d2b Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Wed, 13 Mar 2019 22:35:04 -0400 Subject: [PATCH] Use more AssertJ features --- .../mockwebserver/MockWebServerTest.java | 28 +- .../internal/http2/Http2Server.java | 7 +- .../okhttp3/dnsoverhttps/DnsOverHttps.java | 5 +- .../dnsoverhttps/DnsOverHttpsTest.java | 24 +- .../okhttp3/dnsoverhttps/TestDohMain.java | 6 +- .../http2/hpackjson/HpackJsonUtil.java | 4 +- .../logging/HttpLoggingInterceptorTest.java | 8 +- .../internal/sse/EventSourceRecorder.java | 6 +- .../sse/ServerSentEventIteratorTest.java | 6 +- .../main/java/okhttp3/RecordingCookieJar.java | 4 +- .../main/java/okhttp3/TestTls13Request.java | 7 +- .../src/test/java/okhttp3/CallTest.java | 67 +- .../java/okhttp3/CertificatePinnerTest.java | 11 +- .../okhttp3/ConnectionCoalescingTest.java | 3 +- .../java/okhttp3/ConnectionReuseTest.java | 3 +- .../test/java/okhttp3/ConnectionSpecTest.java | 52 +- .../src/test/java/okhttp3/ConscryptTest.java | 3 +- .../src/test/java/okhttp3/CookieTest.java | 3 +- .../src/test/java/okhttp3/CookiesTest.java | 12 +- .../src/test/java/okhttp3/DispatcherTest.java | 20 +- .../src/test/java/okhttp3/DuplexTest.java | 13 +- .../test/java/okhttp3/EventListenerTest.java | 287 ++++---- .../src/test/java/okhttp3/HeadersTest.java | 69 +- .../src/test/java/okhttp3/HttpUrlTest.java | 456 ++++++------ .../test/java/okhttp3/InterceptorTest.java | 7 +- .../src/test/java/okhttp3/MediaTypeTest.java | 3 +- .../test/java/okhttp3/OkHttpClientTest.java | 9 +- .../test/java/okhttp3/RecordedResponse.java | 21 +- .../java/okhttp3/RecordingEventListener.java | 7 +- .../test/java/okhttp3/URLConnectionTest.java | 675 +++++++++--------- .../internal/DoubleInetAddressDns.java | 4 +- .../internal/cache/DiskLruCacheTest.java | 4 +- .../ConnectionSpecSelectorTest.java | 9 +- .../internal/http/RecordingProxySelector.java | 2 +- .../okhttp3/internal/http2/FrameLogTest.java | 4 +- .../okhttp3/internal/http2/HpackTest.java | 25 +- .../internal/http2/Http2ConnectionTest.java | 21 +- .../okhttp3/internal/http2/Http2Test.java | 3 +- .../internal/http2/HttpOverHttp2Test.java | 374 +++++----- .../okhttp3/internal/tls/ClientAuthTest.java | 3 +- .../internal/ws/WebSocketHttpTest.java | 11 +- .../internal/ws/WebSocketReaderTest.java | 5 +- .../internal/ws/WebSocketRecorder.java | 6 +- .../tls/HandshakeCertificatesTest.java | 23 +- .../java/okhttp3/tls/HeldCertificateTest.java | 14 +- .../main/java/okhttp3/CertificatePinner.java | 5 +- okhttp/src/main/java/okhttp3/Dns.java | 5 +- .../src/main/java/okhttp3/internal/Util.java | 3 +- .../okhttp3/recipes/CustomCipherSuites.java | 4 +- 49 files changed, 1140 insertions(+), 1211 deletions(-) diff --git a/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java b/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java index df4d59b4a..68c4e81db 100644 --- a/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java +++ b/mockwebserver/src/test/java/okhttp3/mockwebserver/MockWebServerTest.java @@ -28,7 +28,6 @@ import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -38,7 +37,6 @@ import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.Protocol; import okhttp3.RecordingHostnameVerifier; -import okhttp3.internal.Util; import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HeldCertificate; import org.junit.After; @@ -48,6 +46,7 @@ import org.junit.runner.Description; import org.junit.runners.model.Statement; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static okhttp3.tls.internal.TlsUtil.localhost; @@ -248,11 +247,7 @@ public final class MockWebServerTest { assertThat(in.read()).isEqualTo(-1); long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); - - assertThat(elapsedMillis >= 500).overridingErrorMessage( - Util.format("Request + Response: %sms", elapsedMillis)).isTrue(); - assertThat(elapsedMillis < 1000).overridingErrorMessage( - Util.format("Request + Response: %sms", elapsedMillis)).isTrue(); + assertThat(elapsedMillis).isBetween(500L, 1000L); } /** @@ -276,11 +271,7 @@ public final class MockWebServerTest { assertThat(in.read()).isEqualTo(-1); long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); - - assertThat(elapsedMillis >= 500).overridingErrorMessage( - Util.format("Request + Response: %sms", elapsedMillis)).isTrue(); - assertThat(elapsedMillis < 1000).overridingErrorMessage( - Util.format("Request + Response: %sms", elapsedMillis)).isTrue(); + assertThat(elapsedMillis).isBetween(500L, 1000L); } /** Delay the response body by sleeping 1s. */ @@ -295,8 +286,7 @@ public final class MockWebServerTest { assertThat(in.read()).isEqualTo('A'); long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); - assertThat(elapsedMillis >= 1000).overridingErrorMessage( - Util.format("Request + Response: %sms", elapsedMillis)).isTrue(); + assertThat(elapsedMillis).isGreaterThanOrEqualTo(1000L); in.close(); } @@ -382,7 +372,7 @@ public final class MockWebServerTest { } @Test public void portImplicitlyStarts() throws IOException { - assertThat(server.getPort() > 0).isTrue(); + assertThat(server.getPort()).isGreaterThan(0); } @Test public void hostnameImplicitlyStarts() throws IOException { @@ -468,7 +458,7 @@ public final class MockWebServerTest { refusedConnection.getResponseCode(); fail("Second connection should be refused"); } catch (ConnectException e ) { - assertThat(e.getMessage().contains("refused")).isTrue(); + assertThat(e.getMessage()).contains("refused"); } } @@ -491,7 +481,7 @@ public final class MockWebServerTest { @Test public void testH2PriorKnowledgeServerFallback() { try { - server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).isEqualTo( @@ -503,7 +493,7 @@ public final class MockWebServerTest { @Test public void testH2PriorKnowledgeServerDuplicates() { try { // Treating this use case as user error - server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); + server.setProtocols(asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).isEqualTo( @@ -513,7 +503,7 @@ public final class MockWebServerTest { } @Test public void testMockWebServerH2PriorKnowledgeProtocol() { - server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)); + server.setProtocols(asList(Protocol.H2_PRIOR_KNOWLEDGE)); assertThat(server.protocols().size()).isEqualTo(1); assertThat(server.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE); diff --git a/mockwebserver/src/test/java/okhttp3/mockwebserver/internal/http2/Http2Server.java b/mockwebserver/src/test/java/okhttp3/mockwebserver/internal/http2/Http2Server.java index b7ca4b248..0bb19125e 100644 --- a/mockwebserver/src/test/java/okhttp3/mockwebserver/internal/http2/Http2Server.java +++ b/mockwebserver/src/test/java/okhttp3/mockwebserver/internal/http2/Http2Server.java @@ -39,6 +39,7 @@ import okio.BufferedSink; import okio.Okio; import okio.Source; +import static java.util.Arrays.asList; import static okhttp3.internal.platform.Platform.INFO; import static okhttp3.tls.internal.TlsUtil.localhost; @@ -125,7 +126,7 @@ public final class Http2Server extends Http2Connection.Listener { } private void send404(Http2Stream stream, String path) throws IOException { - List
responseHeaders = Arrays.asList( + List
responseHeaders = asList( new Header(":status", "404"), new Header(":version", "HTTP/1.1"), new Header("content-type", "text/plain") @@ -137,7 +138,7 @@ public final class Http2Server extends Http2Connection.Listener { } private void serveDirectory(Http2Stream stream, File[] files) throws IOException { - List
responseHeaders = Arrays.asList( + List
responseHeaders = asList( new Header(":status", "200"), new Header(":version", "HTTP/1.1"), new Header("content-type", "text/html; charset=UTF-8") @@ -152,7 +153,7 @@ public final class Http2Server extends Http2Connection.Listener { } private void serveFile(Http2Stream stream, File file) throws IOException { - List
responseHeaders = Arrays.asList( + List
responseHeaders = asList( new Header(":status", "200"), new Header(":version", "HTTP/1.1"), new Header("content-type", contentType(file)) diff --git a/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java b/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java index 67442f331..df56442f4 100644 --- a/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java +++ b/okhttp-dnsoverhttps/src/main/java/okhttp3/dnsoverhttps/DnsOverHttps.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import javax.annotation.Nullable; @@ -40,6 +39,8 @@ import okhttp3.internal.platform.Platform; import okhttp3.internal.publicsuffix.PublicSuffixDatabase; import okio.ByteString; +import static java.util.Arrays.asList; + /** * DNS over HTTPS implementation. * @@ -348,7 +349,7 @@ public class DnsOverHttps implements Dns { } public Builder bootstrapDnsHosts(InetAddress... bootstrapDnsHosts) { - return bootstrapDnsHosts(Arrays.asList(bootstrapDnsHosts)); + return bootstrapDnsHosts(asList(bootstrapDnsHosts)); } public Builder systemDns(Dns systemDns) { diff --git a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java index 6c939bfdb..b4b8df228 100644 --- a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java +++ b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.java @@ -20,8 +20,6 @@ import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.List; import okhttp3.Cache; import okhttp3.Dns; @@ -84,8 +82,8 @@ public class DnsOverHttpsTest { List result = dns.lookup("google.com"); 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(); + assertThat(result).contains(address("157.240.1.18")); + assertThat(result).contains(address("2a03:2880:f029:11:face:b00c:0:2")); RecordedRequest request1 = server.takeRequest(); assertThat(request1.getMethod()).isEqualTo("GET"); @@ -93,10 +91,9 @@ public class DnsOverHttpsTest { RecordedRequest request2 = server.takeRequest(); assertThat(request2.getMethod()).isEqualTo("GET"); - assertThat(new LinkedHashSet<>(Arrays.asList(request1.getPath(), request2.getPath()))).isEqualTo( - new HashSet<>( - Arrays.asList("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", - "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ"))); + assertThat(asList(request1.getPath(), request2.getPath())).containsExactlyInAnyOrder( + "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", + "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ"); } @Test public void failure() throws Exception { @@ -130,9 +127,8 @@ public class DnsOverHttpsTest { } catch (IOException ioe) { assertThat(ioe.getMessage()).isEqualTo("google.com"); Throwable cause = ioe.getCause(); - assertThat(cause instanceof IOException).isTrue(); - assertThat(cause.getMessage()).isEqualTo( - "response size exceeds limit (65536 bytes): 65537 bytes"); + assertThat(cause).isInstanceOf(IOException.class); + assertThat(cause).hasMessage("response size exceeds limit (65536 bytes): 65537 bytes"); } } @@ -143,10 +139,8 @@ public class DnsOverHttpsTest { dns.lookup("google.com"); fail(); } catch (IOException ioe) { - assertThat(ioe.getMessage()).isEqualTo("google.com"); - Throwable cause = ioe.getCause(); - boolean condition = cause instanceof RuntimeException; - assertThat(condition).isTrue(); + assertThat(ioe).hasMessage("google.com"); + assertThat(ioe.getCause()).isInstanceOf(RuntimeException.class); } } diff --git a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.java b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.java index 65975ae5c..cfd76af0e 100644 --- a/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.java +++ b/okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.java @@ -27,13 +27,15 @@ import okhttp3.Cache; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; +import static java.util.Arrays.asList; + public class TestDohMain { public static void main(String[] args) throws IOException { Security.insertProviderAt(new org.conscrypt.OpenSSLProvider(), 1); OkHttpClient bootstrapClient = new OkHttpClient.Builder().build(); - List names = Arrays.asList("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee"); + List names = asList("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee"); try { System.out.println("uncached\n********\n"); @@ -53,7 +55,7 @@ public class TestDohMain { runBatch(badProviders, names); System.out.println("cached first run\n****************\n"); - names = Arrays.asList("google.com", "graph.facebook.com"); + names = asList("google.com", "graph.facebook.com"); bootstrapClient = bootstrapClient.newBuilder().cache(dnsCache).build(); dnsProviders = DohProviders.providers(bootstrapClient, true, true, true); runBatch(dnsProviders, names); diff --git a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.java b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.java index 39b1489d4..9cd88bd87 100644 --- a/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.java +++ b/okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.java @@ -26,6 +26,8 @@ import java.util.Arrays; import java.util.List; import okio.Okio; +import static java.util.Arrays.asList; + /** * Utilities for reading HPACK tests. */ @@ -51,7 +53,7 @@ public final class HpackJsonUtil { File testCaseDirectory = new File(HpackJsonUtil.class.getResource("/hpack-test-case").toURI()); List storyNames = new ArrayList<>(); for (File path : testCaseDirectory.listFiles()) { - if (path.isDirectory() && Arrays.asList(path.list()).contains("story_00.json")) { + if (path.isDirectory() && asList(path.list()).contains("story_00.json")) { try { Story firstStory = readStory(new File(path, "story_00.json")); if (firstStory.getDraft() >= BASE_DRAFT) { 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 a3d18befe..c22b94329 100644 --- a/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java +++ b/okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; -import java.util.regex.Pattern; import javax.annotation.Nullable; import javax.net.ssl.HostnameVerifier; import okhttp3.HttpUrl; @@ -846,17 +845,16 @@ public final class HttpLoggingInterceptorTest { private int index; LogRecorder assertLogEqual(String expected) { - assertThat(index < logs.size()).overridingErrorMessage("No more messages found").isTrue(); + assertThat(index).overridingErrorMessage("No more messages found").isLessThan(logs.size()); String actual = logs.get(index++); assertThat(actual).isEqualTo(expected); return this; } LogRecorder assertLogMatch(String pattern) { - assertThat(index < logs.size()).overridingErrorMessage("No more messages found").isTrue(); + assertThat(index).overridingErrorMessage("No more messages found").isLessThan(logs.size()); String actual = logs.get(index++); - assertThat(Pattern.matches(pattern, actual)).overridingErrorMessage( - "<" + actual + "> did not match pattern <" + pattern + ">").isTrue(); + assertThat(actual).matches(pattern); return this; } 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 ffcf8daa9..bc87c5a64 100644 --- a/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java +++ b/okhttp-sse/src/test/java/okhttp3/internal/sse/EventSourceRecorder.java @@ -19,10 +19,10 @@ import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import javax.annotation.Nullable; -import okhttp3.sse.EventSource; -import okhttp3.sse.EventSourceListener; import okhttp3.Response; import okhttp3.internal.platform.Platform; +import okhttp3.sse.EventSource; +import okhttp3.sse.EventSourceListener; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; @@ -65,7 +65,7 @@ public final class EventSourceRecorder extends EventSourceListener { } public void assertExhausted() { - assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue(); + assertThat(events).isEmpty(); } public void assertEvent(@Nullable String id, @Nullable String type, String data) { 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 77297370a..8959e3168 100644 --- a/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java +++ b/okhttp-sse/src/test/java/okhttp3/internal/sse/ServerSentEventIteratorTest.java @@ -30,9 +30,9 @@ public final class ServerSentEventIteratorTest { private final Deque callbacks = new ArrayDeque<>(); @After public void after() { - assertThat(callbacks.isEmpty()).overridingErrorMessage("Unconsumed events: " + callbacks).isTrue(); + assertThat(callbacks).isEmpty(); } - + @Test public void multiline() throws IOException { consumeEvents("" + "data: YHOO\n" @@ -177,7 +177,7 @@ public final class ServerSentEventIteratorTest { + "\n"); assertThat(callbacks.remove()).isEqualTo(22L); } - + private void consumeEvents(String source) throws IOException { ServerSentEventReader.Callback callback = new ServerSentEventReader.Callback() { @Override public void onEvent(@Nullable String id, @Nullable String type, String data) { diff --git a/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java b/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java index a4988b8e3..eb9e46d9e 100644 --- a/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java +++ b/okhttp-testing-support/src/main/java/okhttp3/RecordingCookieJar.java @@ -17,11 +17,11 @@ package okhttp3; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.List; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public final class RecordingCookieJar implements CookieJar { @@ -29,7 +29,7 @@ public final class RecordingCookieJar implements CookieJar { private final Deque> responseCookies = new ArrayDeque<>(); public void enqueueRequestCookies(Cookie... cookies) { - requestCookies.add(Arrays.asList(cookies)); + requestCookies.add(asList(cookies)); } public List takeResponseCookies() { diff --git a/okhttp-tests/src/main/java/okhttp3/TestTls13Request.java b/okhttp-tests/src/main/java/okhttp3/TestTls13Request.java index ac1bbc7f2..3837efd5c 100644 --- a/okhttp-tests/src/main/java/okhttp3/TestTls13Request.java +++ b/okhttp-tests/src/main/java/okhttp3/TestTls13Request.java @@ -2,11 +2,12 @@ package okhttp3; import java.io.IOException; import java.security.Security; -import java.util.Arrays; import java.util.List; import okhttp3.internal.platform.Platform; import org.conscrypt.Conscrypt; +import static java.util.Arrays.asList; + public class TestTls13Request { // TLS 1.3 @@ -45,7 +46,7 @@ public class TestTls13Request { // https://github.com/tlswg/tls13-spec/wiki/Implementations List urls = - Arrays.asList("https://enabled.tls13.com", "https://www.howsmyssl.com/a/check", + asList("https://enabled.tls13.com", "https://www.howsmyssl.com/a/check", "https://tls13.cloudflare.com", "https://www.allizom.org/robots.txt", "https://tls13.crypto.mozilla.org/", "https://tls.ctf.network/robots.txt", "https://rustls.jbp.io/", "https://h2o.examp1e.net", "https://mew.org/", @@ -75,7 +76,7 @@ public class TestTls13Request { } private static OkHttpClient buildClient(ConnectionSpec... specs) { - return new OkHttpClient.Builder().connectionSpecs(Arrays.asList(specs)).build(); + return new OkHttpClient.Builder().connectionSpecs(asList(specs)).build(); } private static void sendRequest(OkHttpClient client, String url) { diff --git a/okhttp-tests/src/test/java/okhttp3/CallTest.java b/okhttp-tests/src/test/java/okhttp3/CallTest.java index 4cd1ad4db..195cc8b1b 100644 --- a/okhttp-tests/src/test/java/okhttp3/CallTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CallTest.java @@ -62,7 +62,6 @@ import okhttp3.RecordingEventListener.ConnectionReleased; import okhttp3.RecordingEventListener.ResponseFailed; import okhttp3.internal.DoubleInetAddressDns; import okhttp3.internal.RecordingOkAuthenticator; -import okhttp3.internal.Util; import okhttp3.internal.Version; import okhttp3.internal.http.RecordingProxySelector; import okhttp3.internal.io.InMemoryFileSystem; @@ -88,6 +87,7 @@ import org.junit.rules.TestRule; import org.junit.rules.Timeout; import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; +import static java.util.Arrays.asList; import static okhttp3.CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256; import static okhttp3.TestUtil.awaitGarbageCollection; import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion; @@ -205,8 +205,7 @@ public final class CallTest { .assertHeader("B", "123", "234"); RecordedRequest recordedRequest = server.takeRequest(); - assertThat(recordedRequest.getHeaders().values("A")).isEqualTo( - Arrays.asList("345", "456")); + assertThat(recordedRequest.getHeaders().values("A")).containsExactly("345", "456"); } @Test public void repeatedHeaderNames_HTTP_2() throws Exception { @@ -724,8 +723,8 @@ public final class CallTest { bodies.add(firstResponse.getBody()); bodies.add(secondResponse.getBody()); - assertThat(bodies.contains("abc")).isTrue(); - assertThat(bodies.contains("def")).isTrue(); + assertThat(bodies).contains("abc"); + assertThat(bodies).contains("def"); } @Test public void get_Async() throws Exception { @@ -857,8 +856,7 @@ public final class CallTest { // Timed out as expected. long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos); - assertThat(elapsedMillis < 500).overridingErrorMessage( - Util.format("Timed out: %sms", elapsedMillis)).isTrue(); + assertThat(elapsedMillis).isLessThan(500); } finally { bodySource.close(); } @@ -1102,7 +1100,7 @@ public final class CallTest { SSLProtocolException.class, // RI response to the FAIL_HANDSHAKE SSLHandshakeException.class // Android's response to the FAIL_HANDSHAKE ); - assertThat(client.connectionSpecs().contains(ConnectionSpec.COMPATIBLE_TLS)).isFalse(); + assertThat(client.connectionSpecs()).doesNotContain(ConnectionSpec.COMPATIBLE_TLS); } @Test public void recoverFromTlsHandshakeFailure() throws Exception { @@ -1113,7 +1111,7 @@ public final class CallTest { client = client.newBuilder() .hostnameVerifier(new RecordingHostnameVerifier()) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. - .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) + .connectionSpecs(asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .sslSocketFactory( suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) .build(); @@ -1124,7 +1122,7 @@ public final class CallTest { @Test public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception { final String tlsFallbackScsv = "TLS_FALLBACK_SCSV"; List supportedCiphers = - Arrays.asList(handshakeCertificates.sslSocketFactory().getSupportedCipherSuites()); + asList(handshakeCertificates.sslSocketFactory().getSupportedCipherSuites()); if (!supportedCiphers.contains(tlsFallbackScsv)) { // This only works if the client socket supports TLS_FALLBACK_SCSV. return; @@ -1138,7 +1136,7 @@ public final class CallTest { client = client.newBuilder() .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager()) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. - .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) + .connectionSpecs(asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .hostnameVerifier(new RecordingHostnameVerifier()) .build(); @@ -1151,9 +1149,9 @@ public final class CallTest { List clientSockets = clientSocketFactory.getSocketsCreated(); SSLSocket firstSocket = clientSockets.get(0); - assertThat(Arrays.asList(firstSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)).isFalse(); + assertThat(asList(firstSocket.getEnabledCipherSuites())).doesNotContain(tlsFallbackScsv); SSLSocket secondSocket = clientSockets.get(1); - assertThat(Arrays.asList(secondSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)).isTrue(); + assertThat(asList(secondSocket.getEnabledCipherSuites())).contains(tlsFallbackScsv); } @Test public void recoverFromTlsHandshakeFailure_Async() throws Exception { @@ -1164,7 +1162,7 @@ public final class CallTest { client = client.newBuilder() .hostnameVerifier(new RecordingHostnameVerifier()) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. - .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) + .connectionSpecs(asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .sslSocketFactory( suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) .build(); @@ -1179,7 +1177,7 @@ public final class CallTest { @Test public void noRecoveryFromTlsHandshakeFailureWhenTlsFallbackIsDisabled() throws Exception { client = client.newBuilder() - .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) + .connectionSpecs(asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) .hostnameVerifier(new RecordingHostnameVerifier()) .sslSocketFactory( suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) @@ -1247,7 +1245,7 @@ public final class CallTest { .sslSocketFactory( socketFactoryWithCipherSuite(clientCertificates.sslSocketFactory(), cipherSuite), clientCertificates.trustManager()) - .connectionSpecs(Arrays.asList(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) + .connectionSpecs(asList(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .cipherSuites(cipherSuite) .build())) .build(); @@ -1264,7 +1262,7 @@ public final class CallTest { @Test public void cleartextCallsFailWhenCleartextIsDisabled() throws Exception { // Configure the client with only TLS configurations. No cleartext! client = client.newBuilder() - .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) + .connectionSpecs(asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) .build(); server.enqueue(new MockResponse()); @@ -1359,7 +1357,7 @@ public final class CallTest { client.newCall(request).execute(); fail(); } catch (SSLPeerUnverifiedException expected) { - assertThat(expected.getMessage().startsWith("Certificate pinning failure!")).isTrue(); + assertThat(expected.getMessage()).startsWith("Certificate pinning failure!"); } } @@ -2575,8 +2573,7 @@ public final class CallTest { executeSynchronously("/"); RecordedRequest recordedRequest = server.takeRequest(); - assertThat(recordedRequest.getHeader("User-Agent") - .matches(Version.userAgent())).isTrue(); + assertThat(recordedRequest.getHeader("User-Agent")).matches(Version.userAgent()); } @Test public void setFollowRedirectsFalse() throws Exception { @@ -2885,7 +2882,7 @@ public final class CallTest { assertThat(get.getHeader("Private")).isEqualTo("Secret"); assertThat(get.getHeader("User-Agent")).isEqualTo("App 1.0"); - assertThat(hostnameVerifier.calls).isEqualTo(Arrays.asList("verify android.com")); + assertThat(hostnameVerifier.calls).containsExactly("verify android.com"); } /** Respond to a proxy authorization challenge. */ @@ -3147,7 +3144,7 @@ public final class CallTest { assertThat(connect2.getMethod()).isEqualTo("CONNECT"); assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo(credential); - assertThat(challengeSchemes).isEqualTo(Arrays.asList("OkHttp-Preemptive", "Basic")); + assertThat(challengeSchemes).containsExactly("OkHttp-Preemptive", "Basic"); } @Test public void interceptorGetsHttp2() throws Exception { @@ -3284,28 +3281,28 @@ public final class CallTest { upload(true, 1048576, 256); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); - assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); + assertThat(recordedRequest.getChunkSizes()).isNotEmpty(); } @Test public void uploadBodyLargeChunkedEncoding() throws Exception { upload(true, 1048576, 65536); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); - assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); + assertThat(recordedRequest.getChunkSizes()).isNotEmpty(); } @Test public void uploadBodySmallFixedLength() throws Exception { upload(false, 1048576, 256); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); - assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); + assertThat(recordedRequest.getChunkSizes()).isEmpty(); } @Test public void uploadBodyLargeFixedLength() throws Exception { upload(false, 1048576, 65536); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); - assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); + assertThat(recordedRequest.getChunkSizes()).isEmpty(); } private void upload( @@ -3400,10 +3397,10 @@ public final class CallTest { awaitGarbageCollection(); String message = logHandler.take(); - 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(); + assertThat(message).contains("A connection to " + server.url("/") + " was leaked." + + " Did you forget to close a response body?"); + assertThat(message).contains("okhttp3.RealCall.execute("); + assertThat(message).contains("okhttp3.CallTest.leakedResponseBodyLogsStackTrace("); } finally { logger.setLevel(original); } @@ -3443,10 +3440,10 @@ public final class CallTest { awaitGarbageCollection(); String message = logHandler.take(); - 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(); + assertThat(message).contains("A connection to " + server.url("/") + " was leaked." + + " Did you forget to close a response body?"); + assertThat(message).contains("okhttp3.RealCall.enqueue("); + assertThat(message).contains("okhttp3.CallTest.asyncLeakedResponseBodyLogsStackTrace("); } finally { logger.setLevel(original); } @@ -3719,7 +3716,7 @@ public final class CallTest { private void enableProtocol(Protocol protocol) { enableTls(); client = client.newBuilder() - .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) + .protocols(asList(protocol, Protocol.HTTP_1_1)) .build(); server.setProtocols(client.protocols()); } diff --git a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java index 6e57f2cfd..f2e71b001 100644 --- a/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CertificatePinnerTest.java @@ -23,6 +23,7 @@ import okhttp3.CertificatePinner.Pin; import okhttp3.tls.HeldCertificate; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -219,7 +220,7 @@ public final class CertificatePinnerTest { .add("second.com", certC1Sha256Pin) .build(); - List expectedPins = Arrays.asList( + List expectedPins = asList( new Pin("first.com", certA1Sha256Pin), new Pin("first.com", certB1Sha256Pin)); assertThat(certificatePinner.findMatchingPins("first.com")).isEqualTo(expectedPins); @@ -232,7 +233,7 @@ public final class CertificatePinnerTest { .add("b.example.com", certC1Sha256Pin) .build(); - List expectedPins = Arrays.asList( + List expectedPins = asList( new Pin("*.example.com", certA1Sha256Pin), new Pin("a.example.com", certB1Sha256Pin)); assertThat(certificatePinner.findMatchingPins("a.example.com")).isEqualTo(expectedPins); @@ -253,10 +254,10 @@ public final class CertificatePinnerTest { .add("*.MyExample.Com", certB1Sha256Pin) .build(); - List expectedPin1 = Arrays.asList(new Pin("EXAMPLE.com", certA1Sha256Pin)); + List expectedPin1 = asList(new Pin("EXAMPLE.com", certA1Sha256Pin)); assertThat(certificatePinner.findMatchingPins("example.com")).isEqualTo(expectedPin1); - List expectedPin2 = Arrays.asList(new Pin("*.MyExample.Com", certB1Sha256Pin)); + List expectedPin2 = asList(new Pin("*.MyExample.Com", certB1Sha256Pin)); assertThat(certificatePinner.findMatchingPins("a.myexample.com")).isEqualTo(expectedPin2); } @@ -265,7 +266,7 @@ public final class CertificatePinnerTest { .add("σkhttp.com", certA1Sha256Pin) .build(); - List expectedPin = Arrays.asList(new Pin("σkhttp.com", certA1Sha256Pin)); + List expectedPin = asList(new Pin("σkhttp.com", certA1Sha256Pin)); assertThat(certificatePinner.findMatchingPins("xn--khttp-fde.com")).isEqualTo(expectedPin); } diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java index 868057c13..d4493c80f 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionCoalescingTest.java @@ -34,6 +34,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -259,7 +260,7 @@ public final class ConnectionCoalescingTest { HttpUrl sanUrl = url.newBuilder().host("san.com").build(); dns.set("san.com", - Arrays.asList(InetAddress.getByAddress("san.com", new byte[] {0, 0, 0, 0}), + asList(InetAddress.getByAddress("san.com", new byte[] {0, 0, 0, 0}), serverIps.get(0))); assert200Http2Response(execute(sanUrl), "san.com"); diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java index fbce95e42..498f8b3bc 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionReuseTest.java @@ -30,6 +30,7 @@ import org.junit.Test; import org.junit.rules.TestRule; import org.junit.rules.Timeout; +import static java.util.Arrays.asList; import static okhttp3.tls.internal.TlsUtil.localhost; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -355,7 +356,7 @@ public final class ConnectionReuseTest { .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()) .hostnameVerifier(new RecordingHostnameVerifier()) - .protocols(Arrays.asList(protocols)) + .protocols(asList(protocols)) .build(); server.useHttps(handshakeCertificates.sslSocketFactory(), false); server.setProtocols(client.protocols()); diff --git a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java index a889e5c88..79c1f8fbf 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConnectionSpecTest.java @@ -15,14 +15,15 @@ */ package okhttp3; -import java.util.Arrays; -import java.util.LinkedHashSet; +import java.util.ArrayList; +import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -94,13 +95,11 @@ public final class ConnectionSpecTest { assertThat(tlsSpec.isCompatible(socket)).isTrue(); tlsSpec.apply(socket, false /* isFallback */); - assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName)); + assertThat(socket.getEnabledProtocols()).containsExactly(TlsVersion.TLS_1_2.javaName); - Set expectedCipherSet = - set( - CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, - CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); - assertThat(expectedCipherSet).isEqualTo(expectedCipherSet); + assertThat(socket.getEnabledCipherSuites()).containsExactlyInAnyOrder( + CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, + CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); } @Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception { @@ -122,16 +121,15 @@ public final class ConnectionSpecTest { assertThat(tlsSpec.isCompatible(socket)).isTrue(); tlsSpec.apply(socket, true /* isFallback */); - assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName)); + assertThat(socket.getEnabledProtocols()).containsExactly(TlsVersion.TLS_1_2.javaName); - Set expectedCipherSet = - set( - CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, - CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); - if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { - expectedCipherSet.add("TLS_FALLBACK_SCSV"); + List expectedCipherSuites = new ArrayList<>(); + expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); + expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); + if (asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { + expectedCipherSuites.add("TLS_FALLBACK_SCSV"); } - assertThat(expectedCipherSet).isEqualTo(expectedCipherSet); + assertThat(socket.getEnabledCipherSuites()).containsExactlyElementsOf(expectedCipherSuites); } @Test public void tls_explicitCiphers() throws Exception { @@ -154,13 +152,14 @@ public final class ConnectionSpecTest { assertThat(tlsSpec.isCompatible(socket)).isTrue(); tlsSpec.apply(socket, true /* isFallback */); - assertThat(set(socket.getEnabledProtocols())).isEqualTo(set(TlsVersion.TLS_1_2.javaName)); + assertThat(socket.getEnabledProtocols()).containsExactly(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"); + List expectedCipherSuites = new ArrayList<>(); + expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); + if (asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { + expectedCipherSuites.add("TLS_FALLBACK_SCSV"); } - assertThat(expectedCipherSet).isEqualTo(expectedCipherSet); + assertThat(socket.getEnabledCipherSuites()).containsExactlyElementsOf(expectedCipherSuites); } @Test public void tls_stringCiphersAndVersions() throws Exception { @@ -210,7 +209,7 @@ public final class ConnectionSpecTest { }); tlsSpec.apply(sslSocket, false); - assertThat(Arrays.asList(sslSocket.getEnabledCipherSuites())).containsExactly( + assertThat(sslSocket.getEnabledCipherSuites()).containsExactly( CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); } @@ -228,7 +227,7 @@ public final class ConnectionSpecTest { }); tlsSpec.apply(sslSocket, false); - assertThat(Arrays.asList(sslSocket.getEnabledProtocols())).containsExactly( + assertThat(sslSocket.getEnabledProtocols()).containsExactly( TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName()); } @@ -272,7 +271,7 @@ public final class ConnectionSpecTest { assertThat(set.remove(ConnectionSpec.CLEARTEXT)).isTrue(); assertThat(set.remove(allTlsVersions)).isTrue(); assertThat(set.remove(allCipherSuites)).isTrue(); - assertThat(set.isEmpty()).isTrue(); + assertThat(set).isEmpty(); } @Test public void allEnabledToString() throws Exception { @@ -294,9 +293,4 @@ public final class ConnectionSpecTest { ("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], " + "supportsTlsExtensions=true)")); } - - @SafeVarargs - private static Set set(T... values) { - return new LinkedHashSet<>(Arrays.asList(values)); - } } diff --git a/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java b/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java index 5c5184d22..2d2a53566 100644 --- a/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java +++ b/okhttp-tests/src/test/java/okhttp3/ConscryptTest.java @@ -27,6 +27,7 @@ import org.junit.After; import org.junit.Assume; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class ConscryptTest { @@ -53,7 +54,7 @@ public class ConscryptTest { .supportsTlsExtensions(true) .build(); - return new OkHttpClient.Builder().connectionSpecs(Arrays.asList(spec)).build(); + return new OkHttpClient.Builder().connectionSpecs(asList(spec)).build(); } private static void assumeConscrypt() { diff --git a/okhttp-tests/src/test/java/okhttp3/CookieTest.java b/okhttp-tests/src/test/java/okhttp3/CookieTest.java index 31186a842..284fa1e5b 100644 --- a/okhttp-tests/src/test/java/okhttp3/CookieTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CookieTest.java @@ -25,6 +25,7 @@ import okhttp3.internal.Util; import okhttp3.internal.http.HttpDate; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -553,7 +554,7 @@ public final class CookieTest { } @Test public void equalsAndHashCode() throws Exception { - List cookieStrings = Arrays.asList( + List cookieStrings = asList( "a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly", "a= ; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly", "a=b; Domain=example.com; Max-Age=5; Secure; HttpOnly", diff --git a/okhttp-tests/src/test/java/okhttp3/CookiesTest.java b/okhttp-tests/src/test/java/okhttp3/CookiesTest.java index 514252822..857557154 100644 --- a/okhttp-tests/src/test/java/okhttp3/CookiesTest.java +++ b/okhttp-tests/src/test/java/okhttp3/CookiesTest.java @@ -23,7 +23,6 @@ import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URI; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -35,6 +34,7 @@ import org.junit.Rule; import org.junit.Test; import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.Offset.offset; import static org.junit.Assert.fail; @@ -70,7 +70,7 @@ public class CookiesTest { assertThat(cookie.getComment()).isNull(); assertThat(cookie.getCommentURL()).isNull(); assertThat(cookie.getDiscard()).isFalse(); - assertThat(cookie.getMaxAge() > 100000000000L).isTrue(); + assertThat(cookie.getMaxAge()).isGreaterThan(100000000000L); assertThat(cookie.getPath()).isEqualTo("/path"); assertThat(cookie.getSecure()).isTrue(); assertThat(cookie.getVersion()).isEqualTo(0); @@ -280,7 +280,7 @@ public class CookiesTest { JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); HttpUrl url = HttpUrl.get("https://www.squareup.com/"); - cookieJar.saveFromResponse(url, Arrays.asList( + cookieJar.saveFromResponse(url, asList( Cookie.parse(url, "a=android; Domain=squareup.com"))); List actualCookies = cookieJar.loadForRequest(url); assertThat(actualCookies.size()).isEqualTo(1); @@ -293,7 +293,7 @@ public class CookiesTest { JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); HttpUrl url = HttpUrl.get("https://www.squareup.com/"); - cookieJar.saveFromResponse(url, Arrays.asList( + cookieJar.saveFromResponse(url, asList( Cookie.parse(url, "a=android; Domain=.squareup.com"))); List actualCookies = cookieJar.loadForRequest(url); assertThat(actualCookies.size()).isEqualTo(1); @@ -306,7 +306,7 @@ public class CookiesTest { JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); HttpUrl url = HttpUrl.get("https://squareup.com/"); - cookieJar.saveFromResponse(url, Arrays.asList( + cookieJar.saveFromResponse(url, asList( Cookie.parse(url, "a=android; Domain=squareup.com"))); List actualCookies = cookieJar.loadForRequest(url); assertThat(actualCookies.size()).isEqualTo(1); @@ -319,7 +319,7 @@ public class CookiesTest { JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); HttpUrl url1 = HttpUrl.get("https://api.squareup.com/"); - cookieJar.saveFromResponse(url1, Arrays.asList( + cookieJar.saveFromResponse(url1, asList( Cookie.parse(url1, "a=android; Domain=api.squareup.com"))); HttpUrl url2 = HttpUrl.get("https://www.squareup.com/"); diff --git a/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java b/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java index 8d24fc435..c6438e974 100644 --- a/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java +++ b/okhttp-tests/src/test/java/okhttp3/DispatcherTest.java @@ -3,11 +3,8 @@ package okhttp3; import java.io.IOException; import java.io.InterruptedIOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Set; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; @@ -175,8 +172,8 @@ public final class DispatcherTest { a5.enqueue(callback); 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)); + assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2, a3); + assertThat(dispatcher.queuedCalls()).containsExactlyInAnyOrder(a4, a5); } @Test public void synchronousCallAccessors() throws Exception { @@ -205,13 +202,13 @@ public final class DispatcherTest { ready.await(); assertThat(dispatcher.runningCallsCount()).isEqualTo(2); assertThat(dispatcher.queuedCallsCount()).isEqualTo(0); - assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2)); + assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2); assertThat(dispatcher.queuedCalls()).isEmpty(); // Cancel some calls. That doesn't impact running or queued. a2.cancel(); a3.cancel(); - assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2)); + assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2); assertThat(dispatcher.queuedCalls()).isEmpty(); // Let the calls finish. @@ -319,15 +316,6 @@ public final class DispatcherTest { "CallFailed"); } - @SafeVarargs - private final Set set(T... values) { - return set(Arrays.asList(values)); - } - - private Set set(List list) { - return new LinkedHashSet<>(list); - } - private Thread makeSynchronousCall(Call call) { Thread thread = new Thread(() -> { try { diff --git a/okhttp-tests/src/test/java/okhttp3/DuplexTest.java b/okhttp-tests/src/test/java/okhttp3/DuplexTest.java index c67e333b1..0cbc4ee90 100644 --- a/okhttp-tests/src/test/java/okhttp3/DuplexTest.java +++ b/okhttp-tests/src/test/java/okhttp3/DuplexTest.java @@ -18,8 +18,6 @@ package okhttp3; import java.io.IOException; import java.net.HttpURLConnection; import java.net.ProtocolException; -import java.util.Arrays; -import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.internal.RecordingOkAuthenticator; import okhttp3.internal.duplex.AsyncRequestBody; @@ -36,6 +34,7 @@ import org.junit.Test; import org.junit.rules.TestRule; import org.junit.rules.Timeout; +import static java.util.Arrays.asList; import static junit.framework.TestCase.assertTrue; import static okhttp3.tls.internal.TlsUtil.localhost; import static org.assertj.core.api.Assertions.assertThat; @@ -234,12 +233,12 @@ public final class DuplexTest { mockDuplexResponseBody.awaitSuccess(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", + assertThat(listener.recordedEventTypes()).containsExactly( + "CallStart", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestBodyEnd", "ConnectionReleased", "CallEnd"); - assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void duplexWith100Continue() throws Exception { @@ -316,13 +315,13 @@ public final class DuplexTest { mockDuplexResponseBody.awaitSuccess(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", + assertThat(listener.recordedEventTypes()).containsExactly( + "CallStart", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed"); - assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } /** @@ -494,7 +493,7 @@ public final class DuplexTest { private void enableProtocol(Protocol protocol) { enableTls(); client = client.newBuilder() - .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) + .protocols(asList(protocol, Protocol.HTTP_1_1)) .build(); server.setProtocols(client.protocols()); } diff --git a/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java b/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java index 8f614badb..cc60f613c 100644 --- a/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java +++ b/okhttp-tests/src/test/java/okhttp3/EventListenerTest.java @@ -21,7 +21,6 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.UnknownHostException; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -52,22 +51,21 @@ 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; import org.hamcrest.Matcher; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static java.util.Arrays.asList; import static okhttp3.tls.internal.TlsUtil.localhost; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.any; -import static org.hamcrest.CoreMatchers.either; import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; @@ -105,15 +103,14 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.body().string()).isEqualTo("abc"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.body().string()).isEqualTo("abc"); response.body().close(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void successfulCallEventSequenceForEnqueue() throws Exception { @@ -140,11 +137,10 @@ public final class EventListenerTest { completionLatch.await(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void failedCallEventSequence() { @@ -159,14 +155,13 @@ public final class EventListenerTest { call.execute(); fail(); } catch (IOException expected) { - assertThat(expected.getMessage(), either(equalTo("timeout")).or(equalTo("Read timed out"))); + assertThat(expected.getMessage()).isIn("timeout", "Read timed out"); } - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased", "CallFailed"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void failedDribbledCallEventSequence() throws IOException { @@ -188,17 +183,15 @@ public final class EventListenerTest { response.body.string(); fail(); } catch (IOException expected) { - assertThat(expected.getMessage(), equalTo("unexpected end of stream")); + assertThat(expected.getMessage()).isEqualTo("unexpected end of stream"); } - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseFailed", "ConnectionReleased", "CallFailed"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); ResponseFailed responseFailed = listener.removeUpToEvent(ResponseFailed.class); - Assertions.assertThat(responseFailed.ioe.getMessage()).isEqualTo( - "unexpected end of stream"); + assertThat(responseFailed.ioe.getMessage()).isEqualTo("unexpected end of stream"); } @Test public void canceledCallEventSequence() { @@ -210,11 +203,10 @@ public final class EventListenerTest { call.execute(); fail(); } catch (IOException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled"); + assertThat(expected.getMessage()).isEqualTo("Canceled"); } - List expectedEvents = Arrays.asList("CallStart", "CallFailed"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallFailed"); } private void assertSuccessfulEventOrder(Matcher responseMatcher) throws IOException { @@ -222,23 +214,22 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().string(); response.body().close(); assumeThat(response, responseMatcher); - List expectedEvents = asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", + assertThat(listener.recordedEventTypes()).containsExactly( + "CallStart", "DnsStart", "DnsEnd", "ConnectStart", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void secondCallEventSequence() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); server.enqueue(new MockResponse()); server.enqueue(new MockResponse()); @@ -254,11 +245,9 @@ public final class EventListenerTest { Response response = call.execute(); response.close(); - List expectedEvents = asList("CallStart", "ConnectionAcquired", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } private void assertBytesReadWritten(RecordingEventListener listener, @@ -267,34 +256,30 @@ public final class EventListenerTest { if (requestHeaderLength != null) { RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class); - assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength); + Assert.assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength); } else { - Assertions.assertThat(listener.recordedEventTypes().contains("RequestHeadersEnd")).overridingErrorMessage( - "Found RequestHeadersEnd").isFalse(); + assertThat(listener.recordedEventTypes()).doesNotContain("RequestHeadersEnd"); } if (requestBodyBytes != null) { RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class); - assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes); + Assert.assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes); } else { - Assertions.assertThat(listener.recordedEventTypes().contains("RequestBodyEnd")).overridingErrorMessage( - "Found RequestBodyEnd").isFalse(); + assertThat(listener.recordedEventTypes()).doesNotContain("RequestBodyEnd"); } if (responseHeaderLength != null) { ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class); - assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength); + Assert.assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength); } else { - Assertions.assertThat(listener.recordedEventTypes().contains("ResponseHeadersEnd")).overridingErrorMessage( - "Found ResponseHeadersEnd").isFalse(); + assertThat(listener.recordedEventTypes()).doesNotContain("ResponseHeadersEnd"); } if (responseBodyBytes != null) { ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class); - assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes); + Assert.assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes); } else { - Assertions.assertThat(listener.recordedEventTypes().contains("ResponseBodyEnd")).overridingErrorMessage( - "Found ResponseBodyEnd").isFalse(); + assertThat(listener.recordedEventTypes()).doesNotContain("ResponseBodyEnd"); } } @@ -336,7 +321,7 @@ public final class EventListenerTest { @Test public void successfulEmptyH2CallEventSequence() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); server.enqueue(new MockResponse()); assertSuccessfulEventOrder(matchesProtocol(Protocol.HTTP_2)); @@ -347,7 +332,7 @@ public final class EventListenerTest { @Test public void successfulEmptyHttpsCallEventSequence() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_1_1)); server.enqueue(new MockResponse() .setBody("abc")); @@ -359,7 +344,7 @@ public final class EventListenerTest { @Test public void successfulChunkedHttpsCallEventSequence() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_1_1)); server.enqueue( new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2)); @@ -371,7 +356,7 @@ public final class EventListenerTest { @Test public void successfulChunkedH2CallEventSequence() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); server.enqueue( new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2)); @@ -388,17 +373,17 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class); - Assertions.assertThat(dnsStart.call).isSameAs(call); - Assertions.assertThat(dnsStart.domainName).isEqualTo(server.getHostName()); + assertThat(dnsStart.call).isSameAs(call); + assertThat(dnsStart.domainName).isEqualTo(server.getHostName()); DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class); - Assertions.assertThat(dnsEnd.call).isSameAs(call); - Assertions.assertThat(dnsEnd.domainName).isEqualTo(server.getHostName()); - Assertions.assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1); + assertThat(dnsEnd.call).isSameAs(call); + assertThat(dnsEnd.domainName).isEqualTo(server.getHostName()); + assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1); } @Test public void noDnsLookupOnPooledConnection() throws IOException { @@ -410,7 +395,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.code()).isEqualTo(200); + assertThat(response1.code()).isEqualTo(200); response1.body().close(); listener.clearAllEvents(); @@ -419,12 +404,12 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.code()).isEqualTo(200); + assertThat(response2.code()).isEqualTo(200); response2.body().close(); List recordedEvents = listener.recordedEventTypes(); - Assertions.assertThat(recordedEvents.contains("DnsStart")).isFalse(); - Assertions.assertThat(recordedEvents.contains("DnsEnd")).isFalse(); + assertThat(recordedEvents).doesNotContain("DnsStart"); + assertThat(recordedEvents).doesNotContain("DnsEnd"); } @Test public void multipleDnsLookupsForSingleCall() throws IOException { @@ -445,7 +430,7 @@ public final class EventListenerTest { .url("http://fakeurl:" + server.getPort()) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); listener.removeUpToEvent(DnsStart.class); @@ -470,9 +455,8 @@ public final class EventListenerTest { listener.removeUpToEvent(DnsStart.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); - Assertions.assertThat(callFailed.call).isSameAs(call); - boolean condition = callFailed.ioe instanceof UnknownHostException; - Assertions.assertThat(condition).isTrue(); + assertThat(callFailed.call).isSameAs(call); + assertThat(callFailed.ioe).isInstanceOf(UnknownHostException.class); } @Test public void emptyDnsLookup() { @@ -493,9 +477,8 @@ public final class EventListenerTest { listener.removeUpToEvent(DnsStart.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); - Assertions.assertThat(callFailed.call).isSameAs(call); - boolean condition = callFailed.ioe instanceof UnknownHostException; - Assertions.assertThat(condition).isTrue(); + assertThat(callFailed.call).isSameAs(call); + assertThat(callFailed.ioe).isInstanceOf(UnknownHostException.class); } @Test public void successfulConnect() throws IOException { @@ -505,21 +488,21 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + 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); - Assertions.assertThat(connectStart.call).isSameAs(call); - Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); + assertThat(connectStart.call).isSameAs(call); + assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); - Assertions.assertThat(connectEnd.call).isSameAs(call); - Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); + assertThat(connectEnd.call).isSameAs(call); + assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); } @Test public void failedConnect() throws UnknownHostException { @@ -540,15 +523,15 @@ public final class EventListenerTest { InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); - Assertions.assertThat(connectStart.call).isSameAs(call); - Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); + assertThat(connectStart.call).isSameAs(call); + assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class); - Assertions.assertThat(connectFailed.call).isSameAs(call); - Assertions.assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectFailed.protocol).isNull(); - Assertions.assertThat(connectFailed.ioe).isNotNull(); + assertThat(connectFailed.call).isSameAs(call); + assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectFailed.protocol).isNull(); + assertThat(connectFailed.ioe).isNotNull(); } @Test public void multipleConnectsForSingleCall() throws IOException { @@ -565,7 +548,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); listener.removeUpToEvent(ConnectStart.class); @@ -585,21 +568,21 @@ public final class EventListenerTest { .url("http://www.fakeurl") .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + 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); - Assertions.assertThat(connectStart.call).isSameAs(call); - Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress()); + assertThat(connectStart.call).isSameAs(call); + assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress()); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); - Assertions.assertThat(connectEnd.call).isSameAs(call); - Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); + assertThat(connectEnd.call).isSameAs(call); + assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); } @Test public void successfulSocksProxyConnect() throws Exception { @@ -617,21 +600,21 @@ public final class EventListenerTest { .url("http://" + SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS + ":" + server.getPort()) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + 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); - Assertions.assertThat(connectStart.call).isSameAs(call); - Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectStart.proxy).isEqualTo(proxy); + assertThat(connectStart.call).isSameAs(call); + assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectStart.proxy).isEqualTo(proxy); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); - Assertions.assertThat(connectEnd.call).isSameAs(call); - Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); - Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); + assertThat(connectEnd.call).isSameAs(call); + assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); + assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); } @Test public void authenticatingTunnelProxyConnect() throws IOException { @@ -653,13 +636,13 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); listener.removeUpToEvent(ConnectStart.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); - Assertions.assertThat(connectEnd.protocol).isNull(); + assertThat(connectEnd.protocol).isNull(); listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectEnd.class); @@ -673,15 +656,15 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); - Assertions.assertThat(secureStart.call).isSameAs(call); + assertThat(secureStart.call).isSameAs(call); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); - Assertions.assertThat(secureEnd.call).isSameAs(call); - Assertions.assertThat(secureEnd.handshake).isNotNull(); + assertThat(secureEnd.call).isSameAs(call); + assertThat(secureEnd.handshake).isNotNull(); } @Test public void failedSecureConnect() { @@ -699,11 +682,11 @@ public final class EventListenerTest { } SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); - Assertions.assertThat(secureStart.call).isSameAs(call); + assertThat(secureStart.call).isSameAs(call); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); - Assertions.assertThat(callFailed.call).isSameAs(call); - Assertions.assertThat(callFailed.ioe).isNotNull(); + assertThat(callFailed.call).isSameAs(call); + assertThat(callFailed.ioe).isNotNull(); } @Test public void secureConnectWithTunnel() throws IOException { @@ -720,15 +703,15 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); - Assertions.assertThat(secureStart.call).isSameAs(call); + assertThat(secureStart.call).isSameAs(call); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); - Assertions.assertThat(secureEnd.call).isSameAs(call); - Assertions.assertThat(secureEnd.handshake).isNotNull(); + assertThat(secureEnd.call).isSameAs(call); + assertThat(secureEnd.handshake).isNotNull(); } @Test public void multipleSecureConnectsForSingleCall() throws IOException { @@ -745,7 +728,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); listener.removeUpToEvent(SecureConnectStart.class); @@ -769,7 +752,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.code()).isEqualTo(200); + assertThat(response1.code()).isEqualTo(200); response1.body().close(); listener.clearAllEvents(); @@ -778,12 +761,12 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.code()).isEqualTo(200); + assertThat(response2.code()).isEqualTo(200); response2.body().close(); List recordedEvents = listener.recordedEventTypes(); - Assertions.assertThat(recordedEvents.contains("SecureConnectStart")).isFalse(); - Assertions.assertThat(recordedEvents.contains("SecureConnectEnd")).isFalse(); + assertThat(recordedEvents).doesNotContain("SecureConnectStart"); + assertThat(recordedEvents).doesNotContain("SecureConnectEnd"); } @Test public void successfulConnectionFound() throws IOException { @@ -793,12 +776,12 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().close(); ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class); - Assertions.assertThat(connectionAcquired.call).isSameAs(call); - Assertions.assertThat(connectionAcquired.connection).isNotNull(); + assertThat(connectionAcquired.call).isSameAs(call); + assertThat(connectionAcquired.connection).isNotNull(); } @Test public void noConnectionFoundOnFollowUp() throws IOException { @@ -812,12 +795,12 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); listener.removeUpToEvent(ConnectionAcquired.class); List remainingEvents = listener.recordedEventTypes(); - Assertions.assertThat(remainingEvents.contains("ConnectionAcquired")).isFalse(); + assertThat(remainingEvents).doesNotContain("ConnectionAcquired"); } @Test public void pooledConnectionFound() throws IOException { @@ -829,7 +812,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.code()).isEqualTo(200); + assertThat(response1.code()).isEqualTo(200); response1.body().close(); ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class); @@ -839,11 +822,11 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.code()).isEqualTo(200); + assertThat(response2.code()).isEqualTo(200); response2.body().close(); ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class); - Assertions.assertThat(connectionAcquired2.connection).isSameAs( + assertThat(connectionAcquired2.connection).isSameAs( connectionAcquired1.connection); } @@ -859,7 +842,7 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); listener.removeUpToEvent(ConnectionAcquired.class); listener.removeUpToEvent(ConnectionAcquired.class); @@ -867,13 +850,13 @@ public final class EventListenerTest { @Test public void responseBodyFailHttp1OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_1_1)); responseBodyFail(Protocol.HTTP_1_1); } @Test public void responseBodyFailHttp2OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); responseBodyFail(Protocol.HTTP_2); } @@ -896,7 +879,7 @@ public final class EventListenerTest { // soft failure since client may not support depending on Platform assumeThat(response, matchesProtocol(Protocol.HTTP_2)); } - Assertions.assertThat(response.protocol()).isEqualTo(expectedProtocol); + assertThat(response.protocol()).isEqualTo(expectedProtocol); try { response.body.string(); fail(); @@ -904,7 +887,7 @@ public final class EventListenerTest { } CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); - Assertions.assertThat(callFailed.ioe).isNotNull(); + assertThat(callFailed.ioe).isNotNull(); } @Test public void emptyResponseBody() throws IOException { @@ -919,11 +902,10 @@ public final class EventListenerTest { Response response = call.execute(); response.body().close(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void emptyResponseBodyConnectionClose() throws IOException { @@ -937,11 +919,10 @@ public final class EventListenerTest { Response response = call.execute(); response.body().close(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException { @@ -956,22 +937,21 @@ public final class EventListenerTest { Response response = call.execute(); response.body().close(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void requestBodyFailHttp1OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_1_1)); requestBodyFail(); } @Test public void requestBodyFailHttp2OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); requestBodyFail(); } @@ -1012,7 +992,7 @@ public final class EventListenerTest { } CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); - Assertions.assertThat(callFailed.ioe).isNotNull(); + assertThat(callFailed.ioe).isNotNull(); } @Test public void requestBodyMultipleFailuresReportedOnlyOnce() { @@ -1052,22 +1032,22 @@ public final class EventListenerTest { } catch (IOException expected) { } - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", + assertThat(listener.recordedEventTypes()).containsExactly( + "CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void requestBodySuccessHttp1OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_1_1)); requestBodySuccess(RequestBody.create(MediaType.get("text/plain"), "Hello"), equalTo(5L), equalTo(19L)); } @Test public void requestBodySuccessHttp2OverHttps() throws IOException { enableTlsWithTunnel(false); - server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); requestBodySuccess(RequestBody.create(MediaType.get("text/plain"), "Hello"), equalTo(5L), equalTo(19L)); } @@ -1108,15 +1088,14 @@ public final class EventListenerTest { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.body().string()).isEqualTo("abc"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.body().string()).isEqualTo("abc"); response.body().close(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } private void requestBodySuccess(RequestBody body, Matcher requestBodyBytes, @@ -1128,7 +1107,7 @@ public final class EventListenerTest { .post(body) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("World!"); + assertThat(response.body().string()).isEqualTo("World!"); assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength, equalTo(6L)); @@ -1153,13 +1132,12 @@ public final class EventListenerTest { Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); call.execute(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test @@ -1172,16 +1150,15 @@ public final class EventListenerTest { otherServer.enqueue(new MockResponse()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); - Response response = call.execute(); + call.execute(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } @Test public void applicationInterceptorProceedsMultipleTimes() throws Exception { @@ -1191,7 +1168,7 @@ public final class EventListenerTest { client = client.newBuilder() .addInterceptor(chain -> { try (Response a = chain.proceed(chain.request())) { - Assertions.assertThat(a.body().string()).isEqualTo("a"); + assertThat(a.body().string()).isEqualTo("a"); } return chain.proceed(chain.request()); }) @@ -1199,18 +1176,17 @@ public final class EventListenerTest { Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("b"); + assertThat(response.body().string()).isEqualTo("b"); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void applicationInterceptorShortCircuit() throws Exception { @@ -1226,10 +1202,9 @@ public final class EventListenerTest { Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("a"); + assertThat(response.body().string()).isEqualTo("a"); - List expectedEvents = Arrays.asList("CallStart", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); + assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallEnd"); } /** Response headers start, then the entire request body, then response headers end. */ @@ -1246,10 +1221,10 @@ public final class EventListenerTest { Call call = client.newCall(request); call.execute(); - List expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", + assertThat(listener.recordedEventTypes()).containsExactly( + "CallStart", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); - Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents); } } diff --git a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java index ef1e5ed34..4e09a90d8 100644 --- a/okhttp-tests/src/test/java/okhttp3/HeadersTest.java +++ b/okhttp-tests/src/test/java/okhttp3/HeadersTest.java @@ -17,7 +17,6 @@ package okhttp3; import java.io.IOException; import java.time.Instant; -import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; @@ -101,10 +100,10 @@ public final class HeadersTest { .add("ping: pong ") // Value whitespace is trimmed. .add("kit:kat") // Space after colon is not required. .build(); - 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")); + assertThat(headers.values("foo")).containsExactly("bar", "baz", "bak"); + assertThat(headers.values("key")).containsExactly("value"); + assertThat(headers.values("ping")).containsExactly("pong"); + assertThat(headers.values("kit")).containsExactly("kat"); } @Test public void addThrowsOnEmptyName() { @@ -645,45 +644,45 @@ public final class HeadersTest { Headers headers = new Headers.Builder() .add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Basic", singletonMap("realm", "myrealm")), - new Challenge("Digest", Collections.emptyMap()))); + new Challenge("Digest", Collections.emptyMap())); } @Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() { Headers headers = new Headers.Builder() .add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Basic", singletonMap("realm", "myrealm")), - new Challenge("Basic", singletonMap("realm", "myotherrealm")))); + new Challenge("Basic", singletonMap("realm", "myotherrealm"))); } @Test public void separatorsBeforeFirstAuthParam() { Headers headers = new Headers.Builder() .add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "myrealm")))); + new Challenge("Basic", singletonMap("realm", "myrealm"))); } @Test public void onlyCommaBetweenChallenges() { Headers headers = new Headers.Builder() .add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "myrealm")))); + new Challenge("Basic", singletonMap("realm", "myrealm"))); } @Test public void multipleSeparatorsBetweenChallenges() { Headers headers = new Headers.Builder() .add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "myrealm")))); + new Challenge("Basic", singletonMap("realm", "myrealm"))); } @Test public void unknownAuthParams() { @@ -694,9 +693,9 @@ public final class HeadersTest { Map expectedAuthParams = new LinkedHashMap<>(); expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("foo", "bar"); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", expectedAuthParams))); + new Challenge("Basic", expectedAuthParams)); } @Test public void escapedCharactersInQuotedString() { @@ -704,9 +703,9 @@ public final class HeadersTest { .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "my\\\"realm")))); + new Challenge("Basic", singletonMap("realm", "my\\\"realm"))); } @Test public void commaInQuotedStringAndBeforeFirstChallenge() { @@ -714,9 +713,9 @@ public final class HeadersTest { .add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "my, realm,")))); + new Challenge("Basic", singletonMap("realm", "my, realm,"))); } @Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() { @@ -724,8 +723,8 @@ public final class HeadersTest { .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( - new Challenge("Digest", Collections.emptyMap()))); + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( + new Challenge("Digest", Collections.emptyMap())); } @Test public void unescapedDoubleQuoteInQuotedString() { @@ -733,8 +732,8 @@ public final class HeadersTest { .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( - new Challenge("Digest", Collections.emptyMap()))); + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( + new Challenge("Digest", Collections.emptyMap())); } @Ignore("TODO(jwilson): reject parameters that use invalid characters") @@ -743,8 +742,8 @@ public final class HeadersTest { .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=my\"realm") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( - new Challenge("Digest", Collections.emptyMap()))); + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( + new Challenge("Digest", Collections.emptyMap())); } @Test public void token68InsteadOfAuthParams() { @@ -762,8 +761,8 @@ public final class HeadersTest { .add("WWW-Authenticate", "Other abc==, realm=myrealm") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( - new Challenge("Other", singletonMap(null, "abc==")))); + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( + new Challenge("Other", singletonMap(null, "abc=="))); } @Test public void repeatedAuthParamKey() { @@ -781,9 +780,9 @@ public final class HeadersTest { .add("WWW-Authenticate", "Basic realm=myrealm") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Digest", Collections.emptyMap()), - new Challenge("Basic", singletonMap("realm", "myrealm")))); + new Challenge("Basic", singletonMap("realm", "myrealm"))); } @Test public void multipleAuthenticateHeadersInDifferentOrder() { @@ -792,9 +791,9 @@ public final class HeadersTest { .add("WWW-Authenticate", "Digest") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Basic", singletonMap("realm", "myrealm")), - new Challenge("Digest", Collections.emptyMap()))); + new Challenge("Digest", Collections.emptyMap())); } @Test public void multipleBasicAuthenticateHeaders() { @@ -803,9 +802,9 @@ public final class HeadersTest { .add("WWW-Authenticate", "Basic realm=myotherrealm") .build(); - assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( + assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly( new Challenge("Basic", singletonMap("realm", "myrealm")), - new Challenge("Basic", singletonMap("realm", "myotherrealm")))); + new Challenge("Basic", singletonMap("realm", "myotherrealm"))); } @Test public void byteCount() { diff --git a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java index edd04aced..f6db518bd 100644 --- a/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java +++ b/okhttp-tests/src/test/java/okhttp3/HttpUrlTest.java @@ -20,7 +20,6 @@ import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashSet; import okhttp3.UrlComponentEncodingTester.Component; import okhttp3.UrlComponentEncodingTester.Encoding; import org.junit.Ignore; @@ -28,6 +27,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -36,7 +36,7 @@ import static org.junit.Assert.fail; public final class HttpUrlTest { @Parameterized.Parameters(name = "Use get = {0}") public static Collection parameters() { - return Arrays.asList( + return asList( new Object[] { true }, new Object[] { false } ); @@ -169,8 +169,8 @@ public final class HttpUrlTest { 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("#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(); @@ -346,17 +346,17 @@ public final class HttpUrlTest { } @Test public void usernameAndPassword() throws Exception { - assertThat(parse("http://username:password@host/path")).isEqualTo( - parse("http://username:password@host/path")); - assertThat(parse("http://username:@host/path")).isEqualTo( - parse("http://username@host/path")); + assertThat(parse("http://username:password@host/path")) + .isEqualTo(parse("http://username:password@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. assertThat(parse("http://:@host/path")).isEqualTo(parse("http://host/path")); - assertThat(parse("http://:password@@host/path").encodedPassword()).isEqualTo( - "password%40"); + assertThat(parse("http://:password@@host/path").encodedPassword()) + .isEqualTo("password%40"); } @Test public void unprintableCharactersArePercentEncoded() throws Exception { @@ -455,10 +455,10 @@ public final class HttpUrlTest { @Test public void hostIpv6AddressLeadingCompression() throws Exception { 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"); + 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 { @@ -578,8 +578,8 @@ public final class HttpUrlTest { } @Test public void hostIpv6CanonicalForm() throws Exception { - assertThat(parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host()).isEqualTo( - "abcd:ef01:2345:6789:abcd:ef01:2345:6789"); + 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"); @@ -591,10 +591,10 @@ public final class HttpUrlTest { 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: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"); @@ -605,13 +605,13 @@ public final class HttpUrlTest { /** The builder permits square braces but does not require them. */ @Test public void hostIpv6Builder() throws Exception { HttpUrl base = parse("http://example.com/"); - 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]/"); assertThat(base.newBuilder().host("::1").build().toString()).isEqualTo("http://[::1]/"); - assertThat(base.newBuilder().host("::0001").build().toString()).isEqualTo( - "http://[::1]/"); + assertThat(base.newBuilder().host("::0001").build().toString()) + .isEqualTo("http://[::1]/"); } @Test public void hostIpv4CanonicalForm() throws Exception { @@ -762,46 +762,38 @@ public final class HttpUrlTest { @Test public void decodePassword() { 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"); + assertThat(parse("http://user:%F0%9F%8D%A9@host/").password()) + .isEqualTo("\uD83C\uDF69"); } @Test public void decodeSlashCharacterInDecodedPathSegment() { - assertThat(parse("http://host/a%2Fb%2Fc").pathSegments()).isEqualTo( - Arrays.asList("a/b/c")); + assertThat(parse("http://host/a%2Fb%2Fc").pathSegments()).containsExactly("a/b/c"); } @Test public void decodeEmptyPathSegments() { - assertThat(parse("http://host/").pathSegments()).isEqualTo(Arrays.asList("")); + assertThat(parse("http://host/").pathSegments()).containsExactly(""); } @Test public void percentDecode() throws Exception { - 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")); + assertThat(parse("http://host/%00").pathSegments()).containsExactly("\u0000"); + assertThat(parse("http://host/a/%E2%98%83/c").pathSegments()).containsExactly("a", "\u2603", "c"); + assertThat(parse("http://host/a/%F0%9F%8D%A9/c").pathSegments()).containsExactly("a", "\uD83C\uDF69", "c"); + assertThat(parse("http://host/a/%62/c").pathSegments()).containsExactly("a", "b", "c"); + assertThat(parse("http://host/a/%7A/c").pathSegments()).containsExactly("a", "z", "c"); + assertThat(parse("http://host/a/%7a/c").pathSegments()).containsExactly("a", "z", "c"); } @Test public void malformedPercentEncoding() { - 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")); + assertThat(parse("http://host/a%f/b").pathSegments()).containsExactly("a%f", "b"); + assertThat(parse("http://host/%/b").pathSegments()).containsExactly("%", "b"); + assertThat(parse("http://host/%").pathSegments()).containsExactly("%"); + assertThat(parse("http://github.com/%%30%30").pathSegments()).containsExactly("%00"); } @Test public void malformedUtf8Encoding() { // Replace a partial UTF-8 sequence with the Unicode replacement character. - assertThat(parse("http://host/a/%E2%98x/c").pathSegments()).isEqualTo( - Arrays.asList("a", "\ufffdx", "c")); + assertThat(parse("http://host/a/%E2%98x/c").pathSegments()) + .containsExactly("a", "\ufffdx", "c"); } @Test public void incompleteUrlComposition() throws Exception { @@ -820,18 +812,17 @@ public final class HttpUrlTest { } @Test public void builderToString() { - assertThat(parse("https://host.com/path").newBuilder().toString()).isEqualTo( - "https://host.com/path"); + assertThat(parse("https://host.com/path").newBuilder().toString()) + .isEqualTo("https://host.com/path"); } @Test public void incompleteBuilderToString() { - 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"); + 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(new HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString()) + .isEqualTo("//host.com:8080/path"); } @Test public void minimalUrlComposition() throws Exception { @@ -858,8 +849,8 @@ public final class HttpUrlTest { .query("query") .fragment("fragment") .build(); - assertThat(url.toString()).isEqualTo( - "http://username:password@host:8080/path?query#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"); @@ -917,13 +908,13 @@ public final class HttpUrlTest { .query("i:\u0001@/\\?#%j") .fragment("k:\u0001@/\\?#%l") .build(); - 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/" + 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.pathSegments()).containsExactly("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"); @@ -944,13 +935,13 @@ public final class HttpUrlTest { .encodedQuery("i:\u0001@/\\?#%25j") .encodedFragment("k:\u0001@/\\?#%25l") .build(); - 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/" + 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.pathSegments()).containsExactly("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"); @@ -968,7 +959,7 @@ public final class HttpUrlTest { .build(); 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")); + assertThat(url.pathSegments()).containsExactly("a/b", "c"); } @Test public void composeMixingPathSegments() throws Exception { @@ -981,24 +972,22 @@ public final class HttpUrlTest { .build(); 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")); + assertThat(url.encodedPathSegments()).containsExactly("a%2fb", "c", "d%2525e", "f%25g"); + assertThat(url.pathSegments()).containsExactly("a/b", "c", "d%25e", "f%g"); } @Test public void composeWithAddSegment() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - 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/"); + assertThat(base.newBuilder().addPathSegment("").build().encodedPath()) + .isEqualTo("/a/b/c/"); + assertThat(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 { @@ -1010,147 +999,147 @@ public final class HttpUrlTest { HttpUrl base = parse("http://host/a/b/c"); // Add a string with zero slashes: resulting URL gains one slash. - 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("").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. - 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("/").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. - 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"); + 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. - 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("").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. - 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("/").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. - 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"); + 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/"); - assertThat(base.newBuilder().addPathSegments("d\\e").build().encodedPath()).isEqualTo( - "/d/e"); - assertThat(base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath()).isEqualTo( - "/d/e"); + 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"); - assertThat(base.newBuilder().addPathSegments("/d/e///f").build().encodedPath()).isEqualTo( - "/a/b/c//d/e///f"); + 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"); assertThat( - (Object) base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath()).isEqualTo( - "/a/b/c/d/e/%20/"); + (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"); - assertThat(base.newBuilder().addPathSegment(".").build().encodedPath()).isEqualTo( - "/a/b/c"); + assertThat(base.newBuilder().addPathSegment(".").build().encodedPath()) + .isEqualTo("/a/b/c"); } @Test public void addPathSegmentEncodes() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - 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"); + 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"); - assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()).isEqualTo( - "/a/b/"); + assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()) + .isEqualTo("/a/b/"); } @Test public void addPathSegmentDotAndIgnoredCharacter() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertThat(base.newBuilder().addPathSegment(".\n").build().encodedPath()).isEqualTo( - "/a/b/c/.%0A"); + 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"); - assertThat(base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath()).isEqualTo( - "/a/b/c"); + 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"); - assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath()).isEqualTo( - "/a/b/"); + assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath()) + .isEqualTo("/a/b/"); } @Test public void setPathSegment() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - 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"); + 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"); - 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"); + 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"); - assertThat(base.newBuilder().setPathSegment(0, "").build().encodedPath()).isEqualTo( - "//b/c"); - assertThat(base.newBuilder().setPathSegment(2, "").build().encodedPath()).isEqualTo( - "/a/b/"); + 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 { @@ -1187,8 +1176,8 @@ public final class HttpUrlTest { @Test public void setEncodedPathSegmentEncodes() throws Exception { HttpUrl base = parse("http://host/a/b/c"); - assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath()).isEqualTo( - "/%25/b/c"); + assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath()) + .isEqualTo("/%25/b/c"); } @Test public void setEncodedPathSegmentRejectsDot() throws Exception { @@ -1256,7 +1245,7 @@ public final class HttpUrlTest { .removePathSegment(0) .removePathSegment(0) .build(); - assertThat(url.pathSegments()).isEqualTo(Arrays.asList("")); + assertThat(url.pathSegments()).containsExactly(""); assertThat(url.encodedPath()).isEqualTo("/"); } @@ -1271,15 +1260,15 @@ public final class HttpUrlTest { @Test public void toJavaNetUrl() throws Exception { HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment"); URL javaNetUrl = httpUrl.url(); - assertThat(javaNetUrl.toString()).isEqualTo( - "http://username:password@host/path?query#fragment"); + 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(); - assertThat(uri.toString()).isEqualTo( - "http://username:password@host/path?query#fragment"); + assertThat(uri.toString()) + .isEqualTo("http://username:password@host/path?query#fragment"); } @Test public void toUriSpecialQueryCharacters() throws Exception { @@ -1304,10 +1293,10 @@ public final class HttpUrlTest { .host("host") .username("=[]:;\"~|?#@^/$%*") .build(); - 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/"); + 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 { @@ -1317,10 +1306,10 @@ public final class HttpUrlTest { .username("user") .password("=[]:;\"~|?#@^/$%*") .build(); - 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/"); + 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 { @@ -1330,8 +1319,8 @@ public final class HttpUrlTest { .addPathSegment("=[]:;\"~|?#@^/$%*") .build(); 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*"); + assertThat(url.uri().toString()) + .isEqualTo("http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*"); } @Test public void toUriQueryParameterNameSpecialCharacters() throws Exception { @@ -1340,10 +1329,10 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("=[]:;\"~|?#@^/$%*", "a") .build(); - 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.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"); } @@ -1353,10 +1342,10 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("a", "=[]:;\"~|?#@^/$%*") .build(); - 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.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("=[]:;\"~|?#@^/$%*"); } @@ -1376,8 +1365,8 @@ public final class HttpUrlTest { .host("host") .addQueryParameter("a", "!$(),/:;?@[]\\^`{|}~") .build(); - 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.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("!$(),/:;?@[]\\^`{|}~"); } @@ -1418,20 +1407,20 @@ public final class HttpUrlTest { @Test public void toUriWithControlCharacters() throws Exception { // Percent-encoded in the path. 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")); + 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. - 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")); + 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. - assertThat(parse("http://host/#a\u0000b").uri()).isEqualTo( - new URI("http://host/#a%00b")); + 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")); } @@ -1440,21 +1429,21 @@ public final class HttpUrlTest { // Percent-encoded in the path. 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")); + 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. - assertThat(parse("http://host/?a\u000bb").uri()).isEqualTo( - new URI("http://host/?a%0Bb")); + 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")); + 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. - assertThat(parse("http://host/#a\u000bb").uri()).isEqualTo( - new URI("http://host/#a%0Bb")); + 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")); @@ -1472,8 +1461,8 @@ public final class HttpUrlTest { @Test public void fromJavaNetUrl() throws Exception { URL javaNetUrl = new URL("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = HttpUrl.get(javaNetUrl); - assertThat(httpUrl.toString()).isEqualTo( - "http://username:password@host/path?query#fragment"); + assertThat(httpUrl.toString()) + .isEqualTo("http://username:password@host/path?query#fragment"); } @Test public void fromJavaNetUrlUnsupportedScheme() throws Exception { @@ -1484,8 +1473,8 @@ public final class HttpUrlTest { @Test public void fromUri() throws Exception { URI uri = new URI("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = HttpUrl.get(uri); - assertThat(httpUrl.toString()).isEqualTo( - "http://username:password@host/path?query#fragment"); + assertThat(httpUrl.toString()) + .isEqualTo("http://username:password@host/path?query#fragment"); } @Test public void fromUriUnsupportedScheme() throws Exception { @@ -1561,12 +1550,11 @@ public final class HttpUrlTest { .addQueryParameter("a+=& b", "c+=& d") .addQueryParameter("a+=& b", "e+=& f") .build(); - 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.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")); + assertThat(url.queryParameterValues("a+=& b")).containsExactly("c+=& d", "e+=& f"); } @Test public void absentQueryIsZeroNameValuePairs() throws Exception { @@ -1607,8 +1595,7 @@ public final class HttpUrlTest { @Test public void queryParametersWithoutValues() throws Exception { HttpUrl url = parse("http://host/?foo&bar&baz"); assertThat(url.querySize()).isEqualTo(3); - assertThat(url.queryParameterNames()).isEqualTo( - new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz"))); + assertThat(url.queryParameterNames()).containsExactly("foo", "bar", "baz"); assertThat(url.queryParameterValue(0)).isNull(); assertThat(url.queryParameterValue(1)).isNull(); assertThat(url.queryParameterValue(2)).isNull(); @@ -1620,8 +1607,7 @@ public final class HttpUrlTest { @Test public void queryParametersWithEmptyValues() throws Exception { HttpUrl url = parse("http://host/?foo=&bar=&baz="); assertThat(url.querySize()).isEqualTo(3); - assertThat(url.queryParameterNames()).isEqualTo( - new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz"))); + assertThat(url.queryParameterNames()).containsExactly("foo", "bar", "baz"); assertThat(url.queryParameterValue(0)).isEqualTo(""); assertThat(url.queryParameterValue(1)).isEqualTo(""); assertThat(url.queryParameterValue(2)).isEqualTo(""); @@ -1637,7 +1623,7 @@ public final class HttpUrlTest { 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")); + assertThat(url.queryParameterValues("foo[]")).containsExactly("1", "2", "3"); } @Test public void queryParameterLookupWithNonCanonicalEncoding() throws Exception { @@ -1666,8 +1652,8 @@ public final class HttpUrlTest { .fragment("%") .build(); 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.newBuilder().build().toString()) + .isEqualTo("http://%25:%25@host/%25?%25#%25"); assertThat(url.resolve("").toString()).isEqualTo("http://%25:%25@host/%25?%25"); } @@ -1681,13 +1667,13 @@ public final class HttpUrlTest { 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.encodedPathSegments()).containsExactly("%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"); + assertThat(url.resolve("").toString()) + .isEqualTo("http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D"); } @Test public void clearFragment() throws Exception { @@ -1712,12 +1698,12 @@ public final class HttpUrlTest { @Test public void 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"); + 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"); assertThat(parse("https://co.uk").topPrivateDomain()).isNull(); assertThat(parse("https://square").topPrivateDomain()).isNull(); diff --git a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java index 92b580959..8dfe07f7a 100644 --- a/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/InterceptorTest.java @@ -339,12 +339,11 @@ public final class InterceptorTest { .build(); Response response = client.newCall(request).execute(); - assertThat(response.headers("Response-Interceptor")).isEqualTo( - Arrays.asList("Cupcake", "Donut")); + assertThat(response.headers("Response-Interceptor")).containsExactly("Cupcake", "Donut"); RecordedRequest recordedRequest = server.takeRequest(); - assertThat(recordedRequest.getHeaders().values("Request-Interceptor")).isEqualTo( - Arrays.asList("Android", "Bob")); + assertThat(recordedRequest.getHeaders().values("Request-Interceptor")) + .containsExactly("Android", "Bob"); } @Test public void asyncApplicationInterceptors() throws Exception { diff --git a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java index ac4c608f1..497866929 100644 --- a/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java +++ b/okhttp-tests/src/test/java/okhttp3/MediaTypeTest.java @@ -24,6 +24,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -37,7 +38,7 @@ import static org.junit.Assert.fail; public class MediaTypeTest { @Parameterized.Parameters(name = "Use get = {0}") public static Collection parameters() { - return Arrays.asList( + return asList( new Object[] { true }, new Object[] { false } ); diff --git a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java index b999eb285..dc7fb55eb 100644 --- a/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java +++ b/okhttp-tests/src/test/java/okhttp3/OkHttpClientTest.java @@ -28,6 +28,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.defaultClient; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @@ -128,7 +129,7 @@ public final class OkHttpClientTest { @Test public void setProtocolsRejectsHttp10() throws Exception { OkHttpClient.Builder builder = new OkHttpClient.Builder(); try { - builder.protocols(Arrays.asList(Protocol.HTTP_1_0, Protocol.HTTP_1_1)); + builder.protocols(asList(Protocol.HTTP_1_0, Protocol.HTTP_1_1)); fail(); } catch (IllegalArgumentException expected) { } @@ -185,7 +186,7 @@ public final class OkHttpClientTest { @Test public void testH2PriorKnowledgeOkHttpClientConstructionFallback() { try { new OkHttpClient.Builder() - .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); + .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).isEqualTo( @@ -197,7 +198,7 @@ public final class OkHttpClientTest { @Test public void testH2PriorKnowledgeOkHttpClientConstructionDuplicates() { try { new OkHttpClient.Builder() - .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); + .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage()).isEqualTo( @@ -208,7 +209,7 @@ public final class OkHttpClientTest { @Test public void testH2PriorKnowledgeOkHttpClientConstructionSuccess() { OkHttpClient okHttpClient = new OkHttpClient.Builder() - .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)) + .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE)) .build(); assertThat(okHttpClient.protocols().size()).isEqualTo(1); assertThat(okHttpClient.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE); diff --git a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java index 8d502a088..482d78179 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordedResponse.java @@ -53,7 +53,7 @@ public final class RecordedResponse { } public RecordedResponse assertRequestHeader(String name, String... values) { - assertThat(request.headers(name)).isEqualTo(Arrays.asList(values)); + assertThat(request.headers(name)).containsExactly(values); return this; } @@ -73,7 +73,7 @@ public final class RecordedResponse { } public RecordedResponse assertHeader(String name, String... values) { - assertThat(response.headers(name)).isEqualTo(Arrays.asList(values)); + assertThat(response.headers(name)).containsExactly(values); return this; } @@ -148,15 +148,16 @@ public final class RecordedResponse { break; } } - assertThat(found).overridingErrorMessage("Expected exception type among " + Arrays.toString(allowedExceptionTypes) - + ", got " + failure).isTrue(); + assertThat(found) + .overridingErrorMessage("Expected exception type among " + + Arrays.toString(allowedExceptionTypes) + ", got " + failure) + .isTrue(); return this; } public RecordedResponse assertFailure(String... messages) { assertThat(failure).overridingErrorMessage("No failure found").isNotNull(); - assertThat(Arrays.asList(messages).contains(failure.getMessage())).overridingErrorMessage( - failure.getMessage()).isTrue(); + assertThat(messages).contains(failure.getMessage()); return this; } @@ -179,10 +180,10 @@ public final class RecordedResponse { } private void assertDateInRange(long minimum, long actual, long maximum) { - assertThat(actual >= minimum).overridingErrorMessage( - "actual " + format(actual) + " < minimum " + format(maximum)).isTrue(); - assertThat(actual <= maximum).overridingErrorMessage( - "actual " + format(actual) + " > maximum " + format(minimum)).isTrue(); + assertThat(actual) + .overridingErrorMessage("%s <= %s <= %s", format(minimum), format(actual), format(maximum)) + .isBetween(minimum, maximum); + } 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 f3ed94acd..3b9a19ece 100644 --- a/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java +++ b/okhttp-tests/src/test/java/okhttp3/RecordingEventListener.java @@ -20,12 +20,12 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.util.ArrayList; -import java.util.Arrays; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; import javax.annotation.Nullable; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public final class RecordingEventListener extends EventListener { @@ -71,8 +71,7 @@ public final class RecordingEventListener extends EventListener { CallEvent startEvent = e.closes(); if (startEvent != null) { - assertThat(eventSequence.contains(startEvent)).overridingErrorMessage( - e.getName() + " without matching " + startEvent.getName()).isTrue(); + assertThat(eventSequence).contains(startEvent); } eventSequence.offer(e); @@ -175,7 +174,7 @@ public final class RecordingEventListener extends EventListener { CallEvent(Call call, Object... params) { this.call = call; - this.params = Arrays.asList(params); + this.params = asList(params); } public String getName() { diff --git a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java index e44ab7736..bf89a99fb 100644 --- a/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/URLConnectionTest.java @@ -76,7 +76,6 @@ 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; @@ -86,6 +85,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; import static java.util.Locale.US; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; @@ -99,9 +99,7 @@ import static okhttp3.mockwebserver.SocketPolicy.SHUTDOWN_INPUT_AT_END; import static okhttp3.mockwebserver.SocketPolicy.SHUTDOWN_OUTPUT_AT_END; 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.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; @@ -141,12 +139,12 @@ public final class URLConnectionTest { .addHeader("D", "e") .addHeader("D", "f") .build(); - Assertions.assertThat(request.header("D")).isEqualTo("f"); - Assertions.assertThat(request.header("d")).isEqualTo("f"); + assertThat(request.header("D")).isEqualTo("f"); + assertThat(request.header("d")).isEqualTo("f"); Headers requestHeaders = request.headers(); - Assertions.assertThat(new LinkedHashSet<>(requestHeaders.values("D"))).isEqualTo( + assertThat(new LinkedHashSet<>(requestHeaders.values("D"))).isEqualTo( newSet("e", "f")); - Assertions.assertThat(new LinkedHashSet<>(requestHeaders.values("d"))).isEqualTo( + assertThat(new LinkedHashSet<>(requestHeaders.values("d"))).isEqualTo( newSet("e", "f")); try { new Request.Builder() @@ -177,10 +175,10 @@ public final class URLConnectionTest { response.close(); RecordedRequest recordedRequest = server.takeRequest(); - Assertions.assertThat(recordedRequest.getHeaders().values("D")).isEqualTo( - Arrays.asList("e", "f")); - Assertions.assertThat(recordedRequest.getHeader("G")).isNull(); - Assertions.assertThat(recordedRequest.getHeader("null")).isNull(); + assertThat(recordedRequest.getHeaders().values("D")).isEqualTo( + asList("e", "f")); + assertThat(recordedRequest.getHeader("G")).isNull(); + assertThat(recordedRequest.getHeader("null")).isNull(); } @Test public void getRequestPropertyReturnsLastValue() { @@ -189,7 +187,7 @@ public final class URLConnectionTest { .addHeader("A", "value1") .addHeader("A", "value2") .build(); - Assertions.assertThat(request.header("A")).isEqualTo("value2"); + assertThat(request.header("A")).isEqualTo("value2"); } @Test public void responseHeaders() throws Exception { @@ -202,24 +200,24 @@ public final class URLConnectionTest { Request request = newRequest("/"); Response response = getResponse(request); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.message()).isEqualTo("Fantastic"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.message()).isEqualTo("Fantastic"); try { response.header(null); fail(); } catch (NullPointerException expected) { } Headers responseHeaders = response.headers(); - Assertions.assertThat(new LinkedHashSet<>(responseHeaders.values("A"))).isEqualTo( + assertThat(new LinkedHashSet<>(responseHeaders.values("A"))).isEqualTo( newSet("c", "e")); - Assertions.assertThat(new LinkedHashSet<>(responseHeaders.values("a"))).isEqualTo( + 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"); + assertThat(responseHeaders.name(0)).isEqualTo("A"); + assertThat(responseHeaders.value(0)).isEqualTo("c"); + assertThat(responseHeaders.name(1)).isEqualTo("B"); + assertThat(responseHeaders.value(1)).isEqualTo("d"); + assertThat(responseHeaders.name(2)).isEqualTo("A"); + assertThat(responseHeaders.value(2)).isEqualTo("e"); response.body().close(); } @@ -307,7 +305,7 @@ public final class URLConnectionTest { Response response = getResponse(request); assertContent("abc", response); - Assertions.assertThat(server.takeRequest().getBody().readUtf8()).isEqualTo("body"); + 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 @@ -339,11 +337,11 @@ public final class URLConnectionTest { server.enqueue(response); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/foo"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/bar?baz=quux"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/z"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void chunkedConnectionsArePooled() throws Exception { @@ -355,11 +353,11 @@ public final class URLConnectionTest { server.enqueue(response); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/foo"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/bar?baz=quux"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertContent("ABCDEFGHIJKLMNOPQR", getResponse(newRequest("/z"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void serverClosesSocket() throws Exception { @@ -400,7 +398,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); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + 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. @@ -416,8 +414,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(); - Assertions.assertThat(requestAfter.getSequenceNumber() == 0 - || server.getRequestCount() == 3 && server.takeRequest().getSequenceNumber() == 0).isTrue(); + assertThat(requestAfter.getSequenceNumber() == 0 + || server.getRequestCount() == 3 && server.takeRequest().getSequenceNumber() == 0).isTrue(); } enum WriteKind {BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS} @@ -479,13 +477,13 @@ public final class URLConnectionTest { .url(server.url("/")) .post(requestBody) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getBodySize()).isEqualTo(n); + assertThat(request.getBodySize()).isEqualTo(n); if (uploadKind == TransferKind.CHUNKED) { - Assertions.assertThat(request.getChunkSizes().size() > 0).isTrue(); + assertThat(request.getChunkSizes()).isNotEmpty(); } else { - Assertions.assertThat(request.getChunkSizes().isEmpty()).isTrue(); + assertThat(request.getChunkSizes()).isEmpty(); } } @@ -504,7 +502,7 @@ public final class URLConnectionTest { assertContent("this response comes via HTTPS", response); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); } @Test public void connectViaHttpsReusingConnections() throws Exception { @@ -552,8 +550,8 @@ public final class URLConnectionTest { Response response2 = getResponse(newRequest("/")); assertContent("another response via HTTPS", response2); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void connectViaHttpsReusingConnectionsDifferentFactories() throws Exception { @@ -603,7 +601,7 @@ public final class URLConnectionTest { client = client.newBuilder() .hostnameVerifier(new RecordingHostnameVerifier()) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS. - .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) + .connectionSpecs(asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS)) .sslSocketFactory( suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) .build(); @@ -612,12 +610,11 @@ public final class URLConnectionTest { assertContent("this response comes via SSL", response); RecordedRequest failHandshakeRequest = server.takeRequest(); - Assertions.assertThat(failHandshakeRequest.getRequestLine()).isNull(); + assertThat(failHandshakeRequest.getRequestLine()).isNull(); RecordedRequest fallbackRequest = server.takeRequest(); - 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))); + assertThat(fallbackRequest.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(fallbackRequest.getTlsVersion()).isIn(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3); } @Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() { @@ -628,7 +625,7 @@ public final class URLConnectionTest { .setSocketPolicy(FAIL_HANDSHAKE)); client = client.newBuilder() - .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) + .connectionSpecs(asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) .hostnameVerifier(new RecordingHostnameVerifier()) .sslSocketFactory( suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) @@ -638,7 +635,7 @@ public final class URLConnectionTest { getResponse(newRequest("/foo")); fail(); } catch (IOException expected) { - Assertions.assertThat(expected.getSuppressed().length).isEqualTo(1); + assertThat(expected.getSuppressed().length).isEqualTo(1); } } @@ -674,10 +671,10 @@ public final class URLConnectionTest { TlsVersion.TLS_1_3); // v1.2 on OpenJDK 8. RecordedRequest request1 = server.takeRequest(); - Assertions.assertThat(tlsVersions.contains(request1.getTlsVersion())).isTrue(); + assertThat(tlsVersions).contains(request1.getTlsVersion()); RecordedRequest request2 = server.takeRequest(); - Assertions.assertThat(tlsVersions.contains(request2.getTlsVersion())).isTrue(); + assertThat(tlsVersions).contains(request2.getTlsVersion()); } /** @@ -693,10 +690,9 @@ public final class URLConnectionTest { getResponse(newRequest("/foo")); fail(); } catch (SSLHandshakeException expected) { - boolean condition = expected.getCause() instanceof CertificateException; - Assertions.assertThat(condition).isTrue(); + assertThat(expected.getCause()).isInstanceOf(CertificateException.class); } - Assertions.assertThat(server.getRequestCount()).isEqualTo(0); + assertThat(server.getRequestCount()).isEqualTo(0); } @Test public void connectViaProxyUsingProxyArg() throws Exception { @@ -721,9 +717,9 @@ public final class URLConnectionTest { assertContent("this response comes via a proxy", response); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo( "GET http://android.com/foo HTTP/1.1"); - Assertions.assertThat(request.getHeader("Host")).isEqualTo("android.com"); + assertThat(request.getHeader("Host")).isEqualTo("android.com"); } @Test public void contentDisagreesWithContentLengthHeaderBodyTooLong() throws IOException { @@ -796,7 +792,7 @@ public final class URLConnectionTest { .socketFactory(SocketFactory.getDefault()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); } @Test public void connectHttpViaSocketFactory() throws Exception { @@ -869,7 +865,7 @@ public final class URLConnectionTest { assertContent("this response comes via HTTPS", call.execute()); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); } @Test public void connectViaHttpProxyToHttpsUsingProxyArg() throws Exception { @@ -913,15 +909,15 @@ public final class URLConnectionTest { assertContent("this response comes via a secure proxy", call.execute()); RecordedRequest connect = server.takeRequest(); - Assertions.assertThat(connect.getRequestLine()).overridingErrorMessage( + 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"); + assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); RecordedRequest get = server.takeRequest(); - 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")); + assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(get.getHeader("Host")).isEqualTo("android.com"); + assertThat(hostnameVerifier.calls).isEqualTo( + asList("verify android.com")); } /** Tolerate bad https proxy response when using HttpResponseCache. Android bug 6754912. */ @@ -953,9 +949,9 @@ public final class URLConnectionTest { assertContent("response", response); RecordedRequest connect = server.takeRequest(); - Assertions.assertThat(connect.getRequestLine()).isEqualTo( + assertThat(connect.getRequestLine()).isEqualTo( "CONNECT android.com:443 HTTP/1.1"); - Assertions.assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); + assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); } private void initResponseCache() { @@ -992,16 +988,16 @@ public final class URLConnectionTest { assertContent("encrypted response from the origin server", response); RecordedRequest connect = server.takeRequest(); - 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"); + assertThat(connect.getHeader("Private")).isNull(); + assertThat(connect.getHeader("Proxy-Authorization")).isNull(); + assertThat(connect.getHeader("User-Agent")).isEqualTo(Version.userAgent()); + assertThat(connect.getHeader("Host")).isEqualTo("android.com:443"); + assertThat(connect.getHeader("Proxy-Connection")).isEqualTo("Keep-Alive"); RecordedRequest get = server.takeRequest(); - Assertions.assertThat(get.getHeader("Private")).isEqualTo("Secret"); - Assertions.assertThat(hostnameVerifier.calls).isEqualTo( - Arrays.asList("verify android.com")); + assertThat(get.getHeader("Private")).isEqualTo("Secret"); + assertThat(hostnameVerifier.calls).isEqualTo( + asList("verify android.com")); } @Test public void proxyAuthenticateOnConnect() throws Exception { @@ -1030,19 +1026,19 @@ public final class URLConnectionTest { assertContent("A", response); RecordedRequest connect1 = server.takeRequest(); - Assertions.assertThat(connect1.getRequestLine()).isEqualTo( + assertThat(connect1.getRequestLine()).isEqualTo( "CONNECT android.com:443 HTTP/1.1"); - Assertions.assertThat(connect1.getHeader("Proxy-Authorization")).isNull(); + assertThat(connect1.getHeader("Proxy-Authorization")).isNull(); RecordedRequest connect2 = server.takeRequest(); - Assertions.assertThat(connect2.getRequestLine()).isEqualTo( + assertThat(connect2.getRequestLine()).isEqualTo( "CONNECT android.com:443 HTTP/1.1"); - Assertions.assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo( + assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo( ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); RecordedRequest get = server.takeRequest(); - Assertions.assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(get.getHeader("Proxy-Authorization")).isNull(); + assertThat(get.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(get.getHeader("Proxy-Authorization")).isNull(); } // Don't disconnect after building a tunnel with CONNECT @@ -1111,7 +1107,7 @@ public final class URLConnectionTest { }).build(); HttpUrl url = HttpUrl.get("http://android.com/foo"); assertContent("response 1", getResponse(newRequest(url))); - Assertions.assertThat(getResponse(newRequest(url)).code()).isEqualTo(407); + assertThat(getResponse(newRequest(url)).code()).isEqualTo(407); } @Test public void disconnectedConnection() throws IOException { @@ -1122,7 +1118,7 @@ public final class URLConnectionTest { Call call = client.newCall(newRequest("/")); Response response = call.execute(); InputStream in = response.body().byteStream(); - Assertions.assertThat((char) in.read()).isEqualTo('A'); + assertThat((char) in.read()).isEqualTo('A'); call.cancel(); try { // Reading 'B' may succeed if it's buffered. @@ -1158,7 +1154,7 @@ public final class URLConnectionTest { call.execute(); fail("Connection should not be established"); } catch (IOException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled"); + assertThat(expected.getMessage()).isEqualTo("Canceled"); } } @@ -1177,7 +1173,7 @@ public final class URLConnectionTest { @SuppressWarnings("deprecation") @Test public void defaultRequestProperty() { URLConnection.setDefaultRequestProperty("X-testSetDefaultRequestProperty", "A"); - Assertions.assertThat( + assertThat( (Object) URLConnection.getDefaultRequestProperty("X-setDefaultRequestProperty")).isNull(); } @@ -1217,16 +1213,17 @@ public final class URLConnectionTest { server.enqueue(response); InputStream in = getResponse(newRequest("/")).body().byteStream(); - Assertions.assertThat(in.markSupported()).overridingErrorMessage( - "This implementation claims to support mark().").isFalse(); + assertThat(in.markSupported()) + .overridingErrorMessage("This implementation claims to support mark().") + .isFalse(); in.mark(5); - Assertions.assertThat(readAscii(in, 5)).isEqualTo("ABCDE"); + assertThat(readAscii(in, 5)).isEqualTo("ABCDE"); try { in.reset(); fail(); } catch (IOException expected) { } - Assertions.assertThat(readAscii(in, Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(in, Integer.MAX_VALUE)).isEqualTo( "FGHIJKLMNOPQRSTUVWXYZ"); in.close(); assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", getResponse(newRequest("/"))); @@ -1247,10 +1244,10 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(401); - Assertions.assertThat(response.code()).isEqualTo(401); - Assertions.assertThat(response.code()).isEqualTo(401); - Assertions.assertThat(server.getRequestCount()).isEqualTo(1); + assertThat(response.code()).isEqualTo(401); + assertThat(response.code()).isEqualTo(401); + assertThat(response.code()).isEqualTo(401); + assertThat(server.getRequestCount()).isEqualTo(1); response.body().close(); } @@ -1315,13 +1312,13 @@ public final class URLConnectionTest { .addHeader("Content-Encoding: gzip")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "ABCABCABC"); - Assertions.assertThat(response.header("Content-Encoding")).isNull(); - Assertions.assertThat(response.body().contentLength()).isEqualTo(-1L); + assertThat(response.header("Content-Encoding")).isNull(); + assertThat(response.body().contentLength()).isEqualTo(-1L); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); + assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); } @Test public void clientConfiguredGzipContentEncoding() throws Exception { @@ -1335,12 +1332,12 @@ public final class URLConnectionTest { .header("Accept-Encoding", "gzip") .build()); InputStream gunzippedIn = new GZIPInputStream(response.body().byteStream()); - Assertions.assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - Assertions.assertThat(response.body().contentLength()).isEqualTo(bodyBytes.size()); + assertThat(response.body().contentLength()).isEqualTo(bodyBytes.size()); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); + assertThat(request.getHeader("Accept-Encoding")).isEqualTo("gzip"); } @Test public void gzipAndConnectionReuseWithFixedLength() throws Exception { @@ -1368,11 +1365,11 @@ public final class URLConnectionTest { .url(server.url("/")) .header("Accept-Encoding", "custom") .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "ABCDE"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Accept-Encoding")).isEqualTo("custom"); + assertThat(request.getHeader("Accept-Encoding")).isEqualTo("custom"); } /** @@ -1405,16 +1402,16 @@ public final class URLConnectionTest { .url(server.url("/")) .build()); InputStream gunzippedIn = new GZIPInputStream(response1.body().byteStream()); - Assertions.assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(gunzippedIn, Integer.MAX_VALUE)).isEqualTo( "one (gzipped)"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); Response response2 = getResponse(new Request.Builder() .url(server.url("/")) .build()); - Assertions.assertThat(readAscii(response2.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response2.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "two (identity)"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void transparentGzipWorksAfterExceptionRecovery() throws Exception { @@ -1434,9 +1431,9 @@ public final class URLConnectionTest { // This connection will need to be recovered. When it is, transparent gzip should still work! assertContent("b", getResponse(newRequest("/"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Connection is not pooled. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void endOfStreamResponseIsNotPooled() throws Exception { @@ -1448,7 +1445,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); assertContent("{}", response); - Assertions.assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(0); + assertThat(client.connectionPool().idleConnectionCount()).isEqualTo(0); } @Test public void earlyDisconnectDoesntHarmPoolingWithChunkedEncoding() throws Exception { @@ -1471,20 +1468,20 @@ public final class URLConnectionTest { Call call1 = client.newCall(newRequest("/")); Response response1 = call1.execute(); InputStream in1 = response1.body().byteStream(); - Assertions.assertThat(readAscii(in1, 5)).isEqualTo("ABCDE"); + assertThat(readAscii(in1, 5)).isEqualTo("ABCDE"); in1.close(); call1.cancel(); Call call2 = client.newCall(newRequest("/")); Response response2 = call2.execute(); InputStream in2 = response2.body().byteStream(); - Assertions.assertThat(readAscii(in2, 5)).isEqualTo("LMNOP"); + assertThat(readAscii(in2, 5)).isEqualTo("LMNOP"); in2.close(); call2.cancel(); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Connection is pooled! - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void streamDiscardingIsTimely() throws Exception { @@ -1505,15 +1502,14 @@ 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. - Assertions.assertThat(elapsedMillis < 500).overridingErrorMessage( - Util.format("Time to close: %sms", elapsedMillis)).isTrue(); + assertThat(elapsedMillis).isLessThan(500L); // Do another request to confirm that the discarded connection was not pooled. assertContent("A", getResponse(newRequest("/"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Connection is not pooled. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void setChunkedStreamingMode() throws Exception { @@ -1523,12 +1519,12 @@ public final class URLConnectionTest { .url(server.url("/")) .post(TransferKind.CHUNKED.newRequestBody("ABCDEFGHIJKLMNOPQ")) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCDEFGHIJKLMNOPQ"); - Assertions.assertThat(request.getChunkSizes()).isEqualTo( - Arrays.asList("ABCDEFGHIJKLMNOPQ".length())); + assertThat(request.getBody().readUtf8()).isEqualTo("ABCDEFGHIJKLMNOPQ"); + assertThat(request.getChunkSizes()).isEqualTo( + asList("ABCDEFGHIJKLMNOPQ".length())); } @Test public void authenticateWithFixedLengthStreaming() throws Exception { @@ -1556,13 +1552,13 @@ public final class URLConnectionTest { .post(streamingMode.newRequestBody("ABCD")) .build(); Response response = getResponse(request); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); assertContent("Authenticated!", response); // No authorization header for the request... RecordedRequest recordedRequest = server.takeRequest(); - Assertions.assertThat(recordedRequest.getHeader("Authorization")).isNull(); - Assertions.assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("ABCD"); + assertThat(recordedRequest.getHeader("Authorization")).isNull(); + assertThat(recordedRequest.getBody().readUtf8()).isEqualTo("ABCD"); } @Test public void postBodyRetransmittedAfterAuthorizationFail() throws Exception { @@ -1598,29 +1594,29 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, body)) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); response.body().byteStream().close(); RecordedRequest recordedRequest1 = server.takeRequest(); - Assertions.assertThat(recordedRequest1.getMethod()).isEqualTo("POST"); - Assertions.assertThat(recordedRequest1.getBody().readUtf8()).isEqualTo(body); - Assertions.assertThat(recordedRequest1.getHeader("Authorization")).isNull(); + assertThat(recordedRequest1.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest1.getBody().readUtf8()).isEqualTo(body); + assertThat(recordedRequest1.getHeader("Authorization")).isNull(); RecordedRequest recordedRequest2 = server.takeRequest(); - Assertions.assertThat(recordedRequest2.getMethod()).isEqualTo("POST"); - Assertions.assertThat(recordedRequest2.getBody().readUtf8()).isEqualTo(body); - Assertions.assertThat(recordedRequest2.getHeader("Authorization")).isEqualTo( + assertThat(recordedRequest2.getMethod()).isEqualTo("POST"); + assertThat(recordedRequest2.getBody().readUtf8()).isEqualTo(body); + assertThat(recordedRequest2.getHeader("Authorization")).isEqualTo( credential); } @Test public void nonStandardAuthenticationScheme() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Foo"); - Assertions.assertThat(calls).isEqualTo(Collections.emptyList()); + assertThat(calls).isEqualTo(Collections.emptyList()); } @Test public void nonStandardAuthenticationSchemeWithRealm() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Foo realm=\"Bar\""); - Assertions.assertThat(calls.size()).isEqualTo(0); + assertThat(calls.size()).isEqualTo(0); } // Digest auth is currently unsupported. Test that digest requests should fail reasonably. @@ -1630,43 +1626,37 @@ public final class URLConnectionTest { + "realm=\"testrealm@host.com\", qop=\"auth,auth-int\", " + "nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\", " + "opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""); - Assertions.assertThat(calls.size()).isEqualTo(0); + assertThat(calls.size()).isEqualTo(0); } @Test public void allAttributesSetInServerAuthenticationCallbacks() throws Exception { List calls = authCallsForHeader("WWW-Authenticate: Basic realm=\"Bar\""); - Assertions.assertThat(calls.size()).isEqualTo(1); + assertThat(calls.size()).isEqualTo(1); URL url = server.url("/").url(); String call = calls.get(0); - 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(); + assertThat(call).contains("host=" + url.getHost()); + assertThat(call).contains("port=" + url.getPort()); + assertThat(call).contains("site=" + url.getHost()); + assertThat(call).contains("url=" + url); + assertThat(call).contains("type=" + Authenticator.RequestorType.SERVER); + assertThat(call).contains("prompt=Bar"); + assertThat(call).contains("protocol=http"); + assertThat(call.toLowerCase(US)).contains("scheme=basic"); // lowercase for the RI. } @Test public void allAttributesSetInProxyAuthenticationCallbacks() throws Exception { List calls = authCallsForHeader("Proxy-Authenticate: Basic realm=\"Bar\""); - Assertions.assertThat(calls.size()).isEqualTo(1); + assertThat(calls.size()).isEqualTo(1); URL url = server.url("/").url(); String call = calls.get(0); - 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(); + assertThat(call).contains("host=" + url.getHost()); + assertThat(call).contains("port=" + url.getPort()); + assertThat(call).contains("site=" + url.getHost()); + assertThat(call).contains("url=http://android.com"); + assertThat(call).contains("type=" + Authenticator.RequestorType.PROXY); + assertThat(call).contains("prompt=Bar"); + assertThat(call).contains("protocol=http"); + assertThat(call.toLowerCase(US)).contains("scheme=basic"); } private List authCallsForHeader(String authHeader) throws IOException { @@ -1692,7 +1682,7 @@ public final class URLConnectionTest { .build(); response = getResponse(newRequest("/")); } - Assertions.assertThat(response.code()).isEqualTo(responseCode); + assertThat(response.code()).isEqualTo(responseCode); response.body().byteStream().close(); return authenticator.calls; } @@ -1722,7 +1712,7 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, RequestBody.create(null, "abc")) .build(); - Assertions.assertThat(request.method()).isEqualTo(requestMethod); + assertThat(request.method()).isEqualTo(requestMethod); } private void assertMethodForbidsRequestBody(String requestMethod) { @@ -1740,7 +1730,7 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, null) .build(); - Assertions.assertThat(request.method()).isEqualTo(requestMethod); + assertThat(request.method()).isEqualTo(requestMethod); } private void assertMethodForbidsNoRequestBody(String requestMethod) { @@ -1767,9 +1757,9 @@ public final class URLConnectionTest { .url(server.url("/")) .method(requestMethod, null) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); RecordedRequest recordedRequest = server.takeRequest(); - Assertions.assertThat(recordedRequest.getMethod()).isEqualTo(requestMethod); + assertThat(recordedRequest.getMethod()).isEqualTo(requestMethod); } @Test public void shoutcast() throws Exception { @@ -1792,8 +1782,8 @@ public final class URLConnectionTest { .addHeader("icy-metaint:16000") .setBody("mp3 data")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.message()).isEqualTo("OK"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.message()).isEqualTo("OK"); assertContent("mp3 data", response); } @@ -1823,18 +1813,18 @@ public final class URLConnectionTest { .url(server.url("/")) .post(streamingMode.newRequestBody("ABCD")) .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Success!"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); if (streamingMode == TransferKind.FIXED_LENGTH) { - Assertions.assertThat(request.getChunkSizes()).isEqualTo( + assertThat(request.getChunkSizes()).isEqualTo( Collections.emptyList()); } else if (streamingMode == TransferKind.CHUNKED) { - Assertions.assertThat(request.getChunkSizes()).isEqualTo(Arrays.asList(4)); + assertThat(request.getChunkSizes()).containsExactly(4); } - Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); + assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); } @Test public void authenticateWithPost() throws Exception { @@ -1858,20 +1848,20 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, "ABCD")) .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Successful auth!"); // No authorization header for the first request... RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Authorization")).isNull(); + 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(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); - Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("POST / HTTP/1.1"); + assertThat(request.getHeader("Authorization")).isEqualTo( ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); - Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); + assertThat(request.getBody().readUtf8()).isEqualTo("ABCD"); } } @@ -1893,18 +1883,18 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Successful auth!"); // No authorization header for the first request... RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Authorization")).isNull(); + 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(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); - Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(request.getHeader("Authorization")).isEqualTo( ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); } } @@ -1927,21 +1917,21 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Successful auth!"); // No authorization header for the first request... RecordedRequest request1 = server.takeRequest(); - Assertions.assertThat(request1.getHeader("Authorization")).isNull(); + assertThat(request1.getHeader("Authorization")).isNull(); // UTF-8 encoding for the first credential. RecordedRequest request2 = server.takeRequest(); - Assertions.assertThat(request2.getHeader("Authorization")).isEqualTo( + assertThat(request2.getHeader("Authorization")).isEqualTo( "Basic dXNlcm5hbWU6bcO2dG9yaGVhZA=="); // ISO-8859-1 encoding for the second credential. RecordedRequest request3 = server.takeRequest(); - Assertions.assertThat(request3.getHeader("Authorization")).isEqualTo( + assertThat(request3.getHeader("Authorization")).isEqualTo( "Basic dXNlcm5hbWU6bfZ0b3JoZWFk"); } @@ -1966,18 +1956,18 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Successful auth!"); // no authorization header for the first request... RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Authorization")).isNull(); + 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(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); - Assertions.assertThat(request.getHeader("Authorization")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(request.getHeader("Authorization")).isEqualTo( ("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS)); } } @@ -1996,7 +1986,7 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Successful auth!"); } @@ -2022,15 +2012,15 @@ public final class URLConnectionTest { .setBody("This is the new location!")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This is the new location!"); RecordedRequest first = server.takeRequest(); - Assertions.assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); RecordedRequest retry = server.takeRequest(); - Assertions.assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); if (reuse) { - Assertions.assertThat(retry.getSequenceNumber()).overridingErrorMessage( + assertThat(retry.getSequenceNumber()).overridingErrorMessage( "Expected connection reuse").isEqualTo(1); } } @@ -2050,14 +2040,14 @@ public final class URLConnectionTest { .hostnameVerifier(new RecordingHostnameVerifier()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This is the new location!"); RecordedRequest first = server.takeRequest(); - Assertions.assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(first.getRequestLine()).isEqualTo("GET / HTTP/1.1"); RecordedRequest retry = server.takeRequest(); - Assertions.assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(retry.getSequenceNumber()).overridingErrorMessage( + assertThat(retry.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(retry.getSequenceNumber()).overridingErrorMessage( "Expected connection reuse").isEqualTo(1); } @@ -2075,7 +2065,7 @@ public final class URLConnectionTest { .hostnameVerifier(new RecordingHostnameVerifier()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This page has moved!"); } @@ -2089,7 +2079,7 @@ public final class URLConnectionTest { .followSslRedirects(false) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This page has moved!"); } @@ -2111,7 +2101,7 @@ public final class URLConnectionTest { .build(); Response response = getResponse(newRequest("/")); assertContent("This is insecure HTTP!", response); - Assertions.assertThat(response.handshake()).isNull(); + assertThat(response.handshake()).isNull(); } @Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception { @@ -2168,7 +2158,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); assertContent("This is the 2nd server!", response); - Assertions.assertThat(response.request().url()).isEqualTo(server2.url("/")); + 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("/")))); @@ -2176,11 +2166,11 @@ public final class URLConnectionTest { String server1Host = server.getHostName() + ":" + server.getPort(); String server2Host = server2.getHostName() + ":" + server2.getPort(); - Assertions.assertThat(server.takeRequest().getHeader("Host")).isEqualTo(server1Host); - Assertions.assertThat(server2.takeRequest().getHeader("Host")).isEqualTo(server2Host); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + assertThat(server.takeRequest().getHeader("Host")).isEqualTo(server1Host); + assertThat(server2.takeRequest().getHeader("Host")).isEqualTo(server2Host); + assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( "Expected connection reuse").isEqualTo(1); - Assertions.assertThat(server2.takeRequest().getSequenceNumber()).overridingErrorMessage( + assertThat(server2.takeRequest().getSequenceNumber()).overridingErrorMessage( "Expected connection reuse").isEqualTo(1); } @@ -2193,7 +2183,7 @@ public final class URLConnectionTest { MockWebServer proxyServer = (uri.getPort() == server.getPort()) ? server : server2; - return Arrays.asList(proxyServer.toProxyAddress()); + return asList(proxyServer.toProxyAddress()); } @Override public void connectFailed(URI uri, SocketAddress address, IOException failure) { @@ -2212,8 +2202,8 @@ public final class URLConnectionTest { assertContent("This is the 2nd server!", getResponse(newRequest("/a"))); - Assertions.assertThat(proxySelectionRequests).isEqualTo( - Arrays.asList(server.url("/").url().toURI(), server2.url("/").url().toURI())); + assertThat(proxySelectionRequests).isEqualTo( + asList(server.url("/").url().toURI(), server2.url("/").url().toURI())); } @Test public void redirectWithAuthentication() throws Exception { @@ -2232,8 +2222,8 @@ public final class URLConnectionTest { assertContent("Page 2", getResponse(newRequest("/a"))); RecordedRequest redirectRequest = server2.takeRequest(); - Assertions.assertThat(redirectRequest.getHeader("Authorization")).isNull(); - Assertions.assertThat(redirectRequest.getPath()).isEqualTo("/b"); + assertThat(redirectRequest.getHeader("Authorization")).isNull(); + assertThat(redirectRequest.getPath()).isEqualTo("/b"); } @Test public void response300MultipleChoiceWithPost() throws Exception { @@ -2274,15 +2264,15 @@ public final class URLConnectionTest { .url(server.url("/page1")) .post(transferKind.newRequestBody("ABCD")) .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Page 2"); RecordedRequest page1 = server.takeRequest(); - Assertions.assertThat(page1.getRequestLine()).isEqualTo("POST /page1 HTTP/1.1"); - Assertions.assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); + assertThat(page1.getRequestLine()).isEqualTo("POST /page1 HTTP/1.1"); + assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); RecordedRequest page2 = server.takeRequest(); - Assertions.assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); + assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); } @Test public void redirectedPostStripsRequestBodyHeaders() throws Exception { @@ -2297,17 +2287,17 @@ public final class URLConnectionTest { .post(RequestBody.create(MediaType.get("text/plain; charset=utf-8"), "ABCD")) .header("Transfer-Encoding", "identity") .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Page 2"); - Assertions.assertThat(server.takeRequest().getRequestLine()).isEqualTo( + assertThat(server.takeRequest().getRequestLine()).isEqualTo( "POST /page1 HTTP/1.1"); RecordedRequest page2 = server.takeRequest(); - 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(); + assertThat(page2.getRequestLine()).isEqualTo("GET /page2 HTTP/1.1"); + assertThat(page2.getHeader("Content-Length")).isNull(); + assertThat(page2.getHeader("Content-Type")).isNull(); + assertThat(page2.getHeader("Transfer-Encoding")).isNull(); } @Test public void response305UseProxy() throws Exception { @@ -2320,12 +2310,12 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/foo")); // Fails on the RI, which gets "Proxy Response". - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This page has moved!"); RecordedRequest page1 = server.takeRequest(); - Assertions.assertThat(page1.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(server.getRequestCount()).isEqualTo(1); + assertThat(page1.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(server.getRequestCount()).isEqualTo(1); } @Test public void response307WithGet() throws Exception { @@ -2383,26 +2373,26 @@ public final class URLConnectionTest { String responseString = readAscii(response.body().byteStream(), Integer.MAX_VALUE); RecordedRequest page1 = server.takeRequest(); - Assertions.assertThat(page1.getRequestLine()).isEqualTo((method + " /page1 HTTP/1.1")); + assertThat(page1.getRequestLine()).isEqualTo((method + " /page1 HTTP/1.1")); if (method.equals("GET")) { - Assertions.assertThat(responseString).isEqualTo("Page 2"); + assertThat(responseString).isEqualTo("Page 2"); } else if (method.equals("HEAD")) { - Assertions.assertThat(responseString).isEqualTo(""); + assertThat(responseString).isEqualTo(""); } else { // Methods other than GET/HEAD shouldn't follow the redirect. if (method.equals("POST")) { - Assertions.assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); + assertThat(page1.getBody().readUtf8()).isEqualTo("ABCD"); } - Assertions.assertThat(server.getRequestCount()).isEqualTo(1); - Assertions.assertThat(responseString).isEqualTo("This page has moved!"); + assertThat(server.getRequestCount()).isEqualTo(1); + assertThat(responseString).isEqualTo("This page has moved!"); return; } // GET/HEAD requests should have followed the redirect with the same method. - Assertions.assertThat(server.getRequestCount()).isEqualTo(2); + assertThat(server.getRequestCount()).isEqualTo(2); RecordedRequest page2 = server.takeRequest(); - Assertions.assertThat(page2.getRequestLine()).isEqualTo((method + " /page2 HTTP/1.1")); + assertThat(page2.getRequestLine()).isEqualTo((method + " /page2 HTTP/1.1")); } @Test public void follow20Redirects() throws Exception { @@ -2417,7 +2407,7 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/0")); assertContent("Success!", response); - Assertions.assertThat(response.request().url()).isEqualTo(server.url("/20")); + assertThat(response.request().url()).isEqualTo(server.url("/20")); } @Test public void doesNotFollow21Redirects() throws Exception { @@ -2432,7 +2422,7 @@ public final class URLConnectionTest { getResponse(newRequest("/0")); fail(); } catch (ProtocolException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo( + assertThat(expected.getMessage()).isEqualTo( "Too many follow-up requests: 21"); } } @@ -2460,10 +2450,10 @@ public final class URLConnectionTest { assertContent("DEF", getResponse(newRequest("/"))); assertContent("GHI", getResponse(newRequest("/"))); - Assertions.assertThat(hostnameVerifier.calls).isEqualTo( - Arrays.asList("verify " + server.getHostName())); - Assertions.assertThat(trustManager.calls).isEqualTo( - Arrays.asList("checkServerTrusted [CN=localhost 1]")); + assertThat(hostnameVerifier.calls).isEqualTo( + asList("verify " + server.getHostName())); + assertThat(trustManager.calls).isEqualTo( + asList("checkServerTrusted [CN=localhost 1]")); } @Test public void getClientRequestTimeout() throws Exception { @@ -2471,8 +2461,8 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(response.code()).isEqualTo(200); + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Body"); } @@ -2494,15 +2484,15 @@ public final class URLConnectionTest { .post(RequestBody.create(null, "Hello")) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(response.code()).isEqualTo(200); + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "Body"); RecordedRequest request1 = server.takeRequest(); - Assertions.assertThat(request1.getBody().readUtf8()).isEqualTo("Hello"); + assertThat(request1.getBody().readUtf8()).isEqualTo("Hello"); RecordedRequest request2 = server.takeRequest(); - Assertions.assertThat(request2.getBody().readUtf8()).isEqualTo("Hello"); + assertThat(request2.getBody().readUtf8()).isEqualTo("Hello"); } @Test public void streamedBodyWithClientRequestTimeout() throws Exception { @@ -2513,10 +2503,10 @@ public final class URLConnectionTest { .post(TransferKind.CHUNKED.newRequestBody("Hello")) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); assertContent("Body", response); response.close(); - Assertions.assertThat(server.getRequestCount()).isEqualTo(2); + assertThat(server.getRequestCount()).isEqualTo(2); } @Test public void readTimeouts() throws IOException { @@ -2533,9 +2523,9 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); BufferedSource in = response.body().source(); in.timeout().timeout(1000, MILLISECONDS); - Assertions.assertThat(in.readByte()).isEqualTo((byte) 'A'); - Assertions.assertThat(in.readByte()).isEqualTo((byte) 'B'); - Assertions.assertThat(in.readByte()).isEqualTo((byte) 'C'); + assertThat(in.readByte()).isEqualTo((byte) 'A'); + assertThat(in.readByte()).isEqualTo((byte) 'B'); + assertThat(in.readByte()).isEqualTo((byte) 'C'); try { in.readByte(); // If Content-Length was accurate, this would return -1 immediately. fail(); @@ -2602,10 +2592,10 @@ public final class URLConnectionTest { .header("Transfer-encoding", "chunked") .post(TransferKind.CHUNKED.newRequestBody("ABC")) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("ABC"); + assertThat(request.getBody().readUtf8()).isEqualTo("ABC"); } @Test public void connectionCloseInRequest() throws Exception { @@ -2616,13 +2606,13 @@ public final class URLConnectionTest { .url(server.url("/")) .header("Connection", "close") .build()); - Assertions.assertThat(a.code()).isEqualTo(200); + assertThat(a.code()).isEqualTo(200); Response b = getResponse(newRequest("/")); - Assertions.assertThat(b.code()).isEqualTo(200); + assertThat(b.code()).isEqualTo(200); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( "When connection: close is used, each request should get its own connection").isEqualTo( (long) 0); } @@ -2633,13 +2623,13 @@ public final class URLConnectionTest { server.enqueue(new MockResponse()); Response a = getResponse(newRequest("/")); - Assertions.assertThat(a.code()).isEqualTo(200); + assertThat(a.code()).isEqualTo(200); Response b = getResponse(newRequest("/")); - Assertions.assertThat(b.code()).isEqualTo(200); + assertThat(b.code()).isEqualTo(200); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( "When connection: close is used, each request should get its own connection").isEqualTo( (long) 0); } @@ -2653,11 +2643,11 @@ public final class URLConnectionTest { .setBody("This is the new location!")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "This is the new location!"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).overridingErrorMessage( "When connection: close is used, each request should get its own connection").isEqualTo( (long) 0); } @@ -2676,8 +2666,8 @@ public final class URLConnectionTest { assertContent("This is the new page!", getResponse(newRequest("/"))); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void responseCodeDisagreesWithHeaders() { @@ -2689,7 +2679,7 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (IOException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo( + assertThat(expected.getMessage()).isEqualTo( "HTTP 204 had non-zero Content-Length: 25"); } } @@ -2702,9 +2692,9 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); - Assertions.assertThat(in.read()).isEqualTo(254); - Assertions.assertThat(in.read()).isEqualTo(255); - Assertions.assertThat(in.read()).isEqualTo(-1); + assertThat(in.read()).isEqualTo(254); + assertThat(in.read()).isEqualTo(255); + assertThat(in.read()).isEqualTo(-1); } @Test public void flushAfterStreamTransmittedWithChunkedEncoding() throws IOException { @@ -2739,7 +2729,7 @@ public final class URLConnectionTest { }) .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "abc"); try { @@ -2791,7 +2781,7 @@ public final class URLConnectionTest { Response connection1 = getResponse(newRequest("/")); BufferedSource source1 = connection1.body().source(); source1.timeout().timeout(100, TimeUnit.MILLISECONDS); - Assertions.assertThat(readAscii(source1.inputStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(source1.inputStream(), Integer.MAX_VALUE)).isEqualTo( "ABC"); server.shutdown(); try { @@ -2811,10 +2801,10 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); - Assertions.assertThat(readAscii(in, 3)).isEqualTo("ABC"); - Assertions.assertThat(in.read()).isEqualTo(-1); + assertThat(readAscii(in, 3)).isEqualTo("ABC"); + assertThat(in.read()).isEqualTo(-1); // throws IOException in Gingerbread. - Assertions.assertThat(in.read()).isEqualTo(-1); + assertThat(in.read()).isEqualTo(-1); } @Test public void getOutputStreamOnGetFails() { @@ -2835,10 +2825,10 @@ public final class URLConnectionTest { .url(server.url("/")) .post(RequestBody.create(null, "ABC")) .build()); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "A"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Content-Length")).isEqualTo("3"); + assertThat(request.getHeader("Content-Length")).isEqualTo("3"); response.body().close(); } @@ -2846,7 +2836,7 @@ public final class URLConnectionTest { server.enqueue(new MockResponse() .setBody("ABC")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.body().contentLength()).isEqualTo(3L); + assertThat(response.body().contentLength()).isEqualTo(3L); response.body().close(); } @@ -2855,7 +2845,7 @@ public final class URLConnectionTest { .addHeader("Content-Type: text/plain") .setBody("ABC")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.body().contentType()).isEqualTo( + assertThat(response.body().contentType()).isEqualTo( MediaType.get("text/plain")); response.body().close(); } @@ -2865,7 +2855,7 @@ public final class URLConnectionTest { .addHeader("Content-Encoding: identity") .setBody("ABC")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.header("Content-Encoding")).isEqualTo("identity"); + assertThat(response.header("Content-Encoding")).isEqualTo("identity"); response.body().close(); } @@ -2875,10 +2865,10 @@ public final class URLConnectionTest { HttpUrl url = server.url("?query"); Response response = getResponse(newRequest(url)); - Assertions.assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), Integer.MAX_VALUE)).isEqualTo( "A"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /?query HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("GET /?query HTTP/1.1"); } @Test public void doOutputForMethodThatDoesntSupportOutput() { @@ -2913,11 +2903,11 @@ public final class URLConnectionTest { Response response = getResponse(newRequest("/")); InputStream in = response.body().byteStream(); for (int i = 0; i < body.length(); i++) { - Assertions.assertThat(in.available() >= 0).isTrue(); - Assertions.assertThat(in.read()).isEqualTo(body.charAt(i)); + assertThat(in.available()).isGreaterThanOrEqualTo(0); + assertThat(in.read()).isEqualTo(body.charAt(i)); } - Assertions.assertThat(in.available()).isEqualTo(0); - Assertions.assertThat(in.read()).isEqualTo(-1); + assertThat(in.available()).isEqualTo(0); + assertThat(in.read()).isEqualTo(-1); } @Test public void postFailsWithBufferedRequestForSmallRequest() throws Exception { @@ -2974,17 +2964,16 @@ public final class URLConnectionTest { break; } catch (IOException socketException) { // If there's a socket exception, this must have a streamed request body. - Assertions.assertThat(j).isEqualTo(0); - Assertions.assertThat(transferKind == TransferKind.CHUNKED - || transferKind == TransferKind.FIXED_LENGTH).isTrue(); + assertThat(j).isEqualTo(0); + assertThat(transferKind).isIn(TransferKind.CHUNKED, TransferKind.FIXED_LENGTH); } } RecordedRequest requestA = server.takeRequest(); - Assertions.assertThat(requestA.getPath()).isEqualTo("/a"); + assertThat(requestA.getPath()).isEqualTo("/a"); RecordedRequest requestB = server.takeRequest(); - Assertions.assertThat(requestB.getPath()).isEqualTo("/b"); - Assertions.assertThat(requestB.getBody().readUtf8()).isEqualTo(requestBody); + assertThat(requestB.getPath()).isEqualTo("/b"); + assertThat(requestB.getBody().readUtf8()).isEqualTo(requestBody); } @Test public void postBodyRetransmittedOnFailureRecovery() throws Exception { @@ -3005,15 +2994,15 @@ public final class URLConnectionTest { assertContent("def", post); RecordedRequest get = server.takeRequest(); - Assertions.assertThat(get.getSequenceNumber()).isEqualTo(0); + assertThat(get.getSequenceNumber()).isEqualTo(0); RecordedRequest post1 = server.takeRequest(); - Assertions.assertThat(post1.getBody().readUtf8()).isEqualTo("body!"); - Assertions.assertThat(post1.getSequenceNumber()).isEqualTo(1); + assertThat(post1.getBody().readUtf8()).isEqualTo("body!"); + assertThat(post1.getSequenceNumber()).isEqualTo(1); RecordedRequest post2 = server.takeRequest(); - Assertions.assertThat(post2.getBody().readUtf8()).isEqualTo("body!"); - Assertions.assertThat(post2.getSequenceNumber()).isEqualTo(0); + assertThat(post2.getBody().readUtf8()).isEqualTo("body!"); + assertThat(post2.getSequenceNumber()).isEqualTo(0); } @Test public void fullyBufferedPostIsTooShort() { @@ -3092,7 +3081,7 @@ public final class URLConnectionTest { .header("B", "") .build()); assertContent("body", response); - Assertions.assertThat(response.request().header("B")).isEqualTo(""); + assertThat(response.request().header("B")).isEqualTo(""); } @Test public void emptyResponseHeaderValueIsAllowed() throws Exception { @@ -3101,7 +3090,7 @@ public final class URLConnectionTest { .setBody("body")); Response response = getResponse(newRequest("/")); assertContent("body", response); - Assertions.assertThat(response.header("A")).isEqualTo(""); + assertThat(response.header("A")).isEqualTo(""); } @Test public void emptyRequestHeaderNameIsStrict() { @@ -3122,8 +3111,8 @@ public final class URLConnectionTest { .setHeaders(headers.build()) .setBody("body")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.header("")).isEqualTo("A"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.header("")).isEqualTo("A"); response.body().close(); } @@ -3171,10 +3160,10 @@ public final class URLConnectionTest { .setHeaders(headers)); Response response = getResponse(newRequest("/")); - 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"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.header("a\tb")).isEqualTo("c\u007fd"); + assertThat(response.header("\ud83c\udf69")).isEqualTo("\u2615\ufe0f"); + assertThat(response.header("")).isEqualTo("ef"); } @Test @Ignore public void deflateCompression() { @@ -3204,15 +3193,15 @@ public final class URLConnectionTest { .build(); assertContent("A", getResponse(newRequest("/private"))); - Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isNull(); - Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( + assertThat(server.takeRequest().getHeader("Authorization")).isNull(); + assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( credential); - Assertions.assertThat(authenticator.onlyRoute().proxy()).isEqualTo(Proxy.NO_PROXY); + assertThat(authenticator.onlyRoute().proxy()).isEqualTo(Proxy.NO_PROXY); Response response = authenticator.onlyResponse(); - Assertions.assertThat(response.request().url().url().getPath()).isEqualTo("/private"); - Assertions.assertThat(response.challenges()).isEqualTo( - Arrays.asList(new Challenge("Basic", "protected area"))); + assertThat(response.request().url().url().getPath()).isEqualTo("/private"); + assertThat(response.challenges()).isEqualTo( + asList(new Challenge("Basic", "protected area"))); } @Test public void customTokenAuthenticator() throws Exception { @@ -3230,14 +3219,14 @@ public final class URLConnectionTest { .build(); assertContent("A", getResponse(newRequest("/private"))); - Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isNull(); - Assertions.assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( + assertThat(server.takeRequest().getHeader("Authorization")).isNull(); + assertThat(server.takeRequest().getHeader("Authorization")).isEqualTo( "oauthed abc123"); Response response = authenticator.onlyResponse(); - Assertions.assertThat(response.request().url().url().getPath()).isEqualTo("/private"); - Assertions.assertThat(response.challenges()).isEqualTo( - Arrays.asList(new Challenge("Bearer", "oauthed"))); + assertThat(response.request().url().url().getPath()).isEqualTo("/private"); + assertThat(response.challenges()).isEqualTo( + asList(new Challenge("Bearer", "oauthed"))); } @Test public void authenticateCallsTrackedAsRedirects() throws Exception { @@ -3258,11 +3247,11 @@ public final class URLConnectionTest { assertContent("c", getResponse(newRequest("/a"))); Response challengeResponse = authenticator.responses.get(0); - Assertions.assertThat(challengeResponse.request().url().url().getPath()).isEqualTo( + assertThat(challengeResponse.request().url().url().getPath()).isEqualTo( "/b"); Response redirectedBy = challengeResponse.priorResponse(); - Assertions.assertThat(redirectedBy.request().url().url().getPath()).isEqualTo("/a"); + assertThat(redirectedBy.request().url().url().getPath()).isEqualTo("/a"); } @Test public void attemptAuthorization20Times() throws Exception { @@ -3297,7 +3286,7 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (ProtocolException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo( + assertThat(expected.getMessage()).isEqualTo( "Too many follow-up requests: 21"); } } @@ -3311,10 +3300,10 @@ public final class URLConnectionTest { server.enqueue(new MockResponse() .setBody("A")); client = client.newBuilder() - .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) + .protocols(asList(protocol, Protocol.HTTP_1_1)) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.protocol()).isEqualTo(protocol); + assertThat(response.protocol()).isEqualTo(protocol); assertContent("A", response); } @@ -3322,14 +3311,14 @@ public final class URLConnectionTest { server.enqueue(new MockResponse() .setStatus("HTTP/1.0 200 OK")); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.protocol()).isEqualTo(Protocol.HTTP_1_0); + 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("/")); - Assertions.assertThat(response.protocol()).isEqualTo(Protocol.HTTP_1_1); + assertThat(response.protocol()).isEqualTo(Protocol.HTTP_1_1); } /** For example, empty Protobuf RPC messages end up as a zero-length POST. */ @@ -3361,16 +3350,16 @@ public final class URLConnectionTest { .build()); assertContent("", response); RecordedRequest zeroLengthPayload = server.takeRequest(); - Assertions.assertThat(zeroLengthPayload.getMethod()).isEqualTo(method); - Assertions.assertThat(zeroLengthPayload.getHeader("content-length")).isEqualTo("0"); - Assertions.assertThat(zeroLengthPayload.getBodySize()).isEqualTo(0L); + assertThat(zeroLengthPayload.getMethod()).isEqualTo(method); + assertThat(zeroLengthPayload.getHeader("content-length")).isEqualTo("0"); + assertThat(zeroLengthPayload.getBodySize()).isEqualTo(0L); } @Test public void setProtocols() throws Exception { server.enqueue(new MockResponse() .setBody("A")); client = client.newBuilder() - .protocols(Arrays.asList(Protocol.HTTP_1_1)) + .protocols(asList(Protocol.HTTP_1_1)) .build(); assertContent("A", getResponse(newRequest("/"))); } @@ -3378,7 +3367,7 @@ public final class URLConnectionTest { @Test public void setProtocolsWithoutHttp11() { try { new OkHttpClient.Builder() - .protocols(Arrays.asList(Protocol.HTTP_2)); + .protocols(asList(Protocol.HTTP_2)); fail(); } catch (IllegalArgumentException expected) { } @@ -3387,7 +3376,7 @@ public final class URLConnectionTest { @Test public void setProtocolsWithNull() { try { new OkHttpClient.Builder() - .protocols(Arrays.asList(Protocol.HTTP_1_1, null)); + .protocols(asList(Protocol.HTTP_1_1, null)); fail(); } catch (IllegalArgumentException expected) { } @@ -3423,7 +3412,7 @@ public final class URLConnectionTest { assertContent("", response); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Content-Length")).isEqualTo( + assertThat(request.getHeader("Content-Length")).isEqualTo( Long.toString(contentLength)); } @@ -3467,19 +3456,19 @@ public final class URLConnectionTest { .setBody("b")); Response response1 = getResponse(newRequest("/")); - Assertions.assertThat(response1.code()).isEqualTo( + assertThat(response1.code()).isEqualTo( (long) HttpURLConnection.HTTP_NOT_MODIFIED); assertContent("", response1); Response response2 = getResponse(newRequest("/")); - Assertions.assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); + assertThat(response2.code()).isEqualTo(HttpURLConnection.HTTP_OK); assertContent("b", response2); RecordedRequest requestA = server.takeRequest(); - Assertions.assertThat(requestA.getSequenceNumber()).isEqualTo(0); + assertThat(requestA.getSequenceNumber()).isEqualTo(0); RecordedRequest requestB = server.takeRequest(); - Assertions.assertThat(requestB.getSequenceNumber()).isEqualTo(1); + assertThat(requestB.getSequenceNumber()).isEqualTo(1); } @Test public void nullSSLSocketFactory_throws() { @@ -3507,10 +3496,10 @@ public final class URLConnectionTest { assertContent("This is the new page!", response); RecordedRequest requestA = server.takeRequest(); - Assertions.assertThat(requestA.getSequenceNumber()).isEqualTo(0); + assertThat(requestA.getSequenceNumber()).isEqualTo(0); RecordedRequest requestB = server.takeRequest(); - Assertions.assertThat(requestB.getSequenceNumber()).isEqualTo(1); + assertThat(requestB.getSequenceNumber()).isEqualTo(1); } /** @@ -3524,11 +3513,11 @@ public final class URLConnectionTest { .url(server.url("/")) .delete(RequestBody.create(null, "BODY")) .build()); - Assertions.assertThat(response.code()).isEqualTo(200); + assertThat(response.code()).isEqualTo(200); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getMethod()).isEqualTo("DELETE"); - Assertions.assertThat(request.getBody().readUtf8()).isEqualTo("BODY"); + assertThat(request.getMethod()).isEqualTo("DELETE"); + assertThat(request.getBody().readUtf8()).isEqualTo("BODY"); } @Test public void userAgentDefaultsToOkHttpVersion() throws Exception { @@ -3538,7 +3527,7 @@ public final class URLConnectionTest { assertContent("abc", getResponse(newRequest("/"))); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("User-Agent")).isEqualTo(Version.userAgent()); + assertThat(request.getHeader("User-Agent")).isEqualTo(Version.userAgent()); } @Test public void urlWithSpaceInHost() { @@ -3572,8 +3561,8 @@ public final class URLConnectionTest { .addHeaderLenient("Location", redirectUrl)); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(302); - Assertions.assertThat(response.header("Location")).isEqualTo(redirectUrl); + assertThat(response.code()).isEqualTo(302); + assertThat(response.header("Location")).isEqualTo(redirectUrl); } @Test public void urlWithBadAsciiHost() { @@ -3609,7 +3598,7 @@ public final class URLConnectionTest { getResponse(newRequest("/")); fail(); } catch (RuntimeException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo("boom!"); + assertThat(expected.getMessage()).isEqualTo("boom!"); } } @@ -3634,11 +3623,11 @@ public final class URLConnectionTest { .build())); RecordedRequest request1 = server.takeRequest(); - Assertions.assertThat(request1.getSequenceNumber()).isEqualTo(0); + assertThat(request1.getSequenceNumber()).isEqualTo(0); RecordedRequest request2 = server.takeRequest(); - Assertions.assertThat(request2.getBody().readUtf8()).isEqualTo("123"); - Assertions.assertThat(request2.getSequenceNumber()).isEqualTo(0); + assertThat(request2.getBody().readUtf8()).isEqualTo("123"); + assertThat(request2.getSequenceNumber()).isEqualTo(0); } @Test public void authenticateNoConnection() throws Exception { @@ -3652,7 +3641,7 @@ public final class URLConnectionTest { .authenticator(new JavaNetAuthenticator()) .build(); Response response = getResponse(newRequest("/")); - Assertions.assertThat(response.code()).isEqualTo(401); + assertThat(response.code()).isEqualTo(401); } private Request newRequest(String s) { @@ -3680,7 +3669,7 @@ public final class URLConnectionTest { private void assertContent(String expected, Response response, int limit) throws IOException { - Assertions.assertThat(readAscii(response.body().byteStream(), limit)).isEqualTo( + assertThat(readAscii(response.body().byteStream(), limit)).isEqualTo( expected); } @@ -3689,7 +3678,7 @@ public final class URLConnectionTest { } private Set newSet(String... elements) { - return new LinkedHashSet<>(Arrays.asList(elements)); + return new LinkedHashSet<>(asList(elements)); } enum TransferKind { @@ -3847,7 +3836,7 @@ public final class URLConnectionTest { .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()) .hostnameVerifier(new RecordingHostnameVerifier()) - .protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) + .protocols(asList(protocol, Protocol.HTTP_1_1)) .build(); server.useHttps(handshakeCertificates.sslSocketFactory(), false); server.setProtocolNegotiationEnabled(true); diff --git a/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java b/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java index 7811ff5d7..84b4b0f61 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/DoubleInetAddressDns.java @@ -21,6 +21,8 @@ import java.util.Arrays; import java.util.List; import okhttp3.Dns; +import static java.util.Arrays.asList; + /** * A network that always resolves two IP addresses per host. Use this when testing route selection * fallbacks to guarantee that a fallback address is available. @@ -28,6 +30,6 @@ import okhttp3.Dns; public class DoubleInetAddressDns implements Dns { @Override public List lookup(String hostname) throws UnknownHostException { List addresses = Dns.SYSTEM.lookup(hostname); - return Arrays.asList(addresses.get(0), addresses.get(0)); + return asList(addresses.get(0), addresses.get(0)); } } 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 9e8f2a989..98e8f76af 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/cache/DiskLruCacheTest.java @@ -19,7 +19,6 @@ import java.io.File; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Arrays; import java.util.Deque; import java.util.Iterator; import java.util.List; @@ -38,6 +37,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; +import static java.util.Arrays.asList; import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE; import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE_BACKUP; import static okhttp3.internal.cache.DiskLruCache.MAGIC; @@ -1650,7 +1650,7 @@ public final class DiskLruCacheTest { expectedLines.add("100"); expectedLines.add("2"); expectedLines.add(""); - expectedLines.addAll(Arrays.asList(expectedBodyLines)); + expectedLines.addAll(asList(expectedBodyLines)); assertThat(readJournalLines()).isEqualTo(expectedLines); } 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 f0c47d76d..625e882b1 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/connection/ConnectionSpecSelectorTest.java @@ -18,8 +18,6 @@ package okhttp3.internal.connection; import java.io.IOException; import java.security.cert.CertificateException; import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; import okhttp3.ConnectionSpec; @@ -28,6 +26,7 @@ import okhttp3.internal.Internal; import okhttp3.tls.HandshakeCertificates; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.tls.internal.TlsUtil.localhost; import static org.assertj.core.api.Assertions.assertThat; @@ -118,7 +117,7 @@ public class ConnectionSpecSelectorTest { private static ConnectionSpecSelector createConnectionSpecSelector( ConnectionSpec... connectionSpecs) { - return new ConnectionSpecSelector(Arrays.asList(connectionSpecs)); + return new ConnectionSpecSelector(asList(connectionSpecs)); } private SSLSocket createSocketWithEnabledProtocols(TlsVersion... tlsVersions) throws IOException { @@ -128,9 +127,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))); - assertThat(actual).isEqualTo(expected); + assertThat(socket.getEnabledProtocols()).containsExactlyInAnyOrder(javaNames(required)); } private static String[] javaNames(TlsVersion... tlsVersions) { 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 dafaae89f..f7b2d5891 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http/RecordingProxySelector.java @@ -39,7 +39,7 @@ public final class RecordingProxySelector extends ProxySelector { } public void assertRequests(URI... expectedUris) { - assertThat(requestedUris).isEqualTo(Arrays.asList(expectedUris)); + assertThat(requestedUris).containsExactly(expectedUris); requestedUris.clear(); } 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 ee21f46c8..d3bc42b19 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/FrameLogTest.java @@ -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)); - assertThat(formattedFlags).isEqualTo(Arrays.asList( + assertThat(formattedFlags).containsExactly( "", "END_STREAM", "00000010", @@ -157,6 +157,6 @@ public final class FrameLogTest { "00111101", "00111110", "00111111" - )); + ); } } 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 69dd07923..90a7d7290 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/HpackTest.java @@ -23,6 +23,7 @@ import okio.ByteString; import org.junit.Before; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.headerEntries; import static okio.ByteString.decodeHex; import static org.assertj.core.api.Assertions.assertThat; @@ -497,8 +498,8 @@ public final class HpackTest { hpackReader.readHeaders(); - assertThat(hpackReader.getAndResetHeaderList()).isEqualTo( - Arrays.asList(new Header("www-authenticate", "Basic"))); + assertThat(hpackReader.getAndResetHeaderList()) + .containsExactly(new Header("www-authenticate", "Basic")); } @Test public void readLiteralHeaderWithIncrementalIndexingDynamicName() throws IOException { @@ -514,8 +515,8 @@ public final class HpackTest { hpackReader.readHeaders(); - assertThat(hpackReader.getAndResetHeaderList()).isEqualTo( - Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2"))); + assertThat(hpackReader.getAndResetHeaderList()).containsExactly( + new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2")); } /** @@ -850,7 +851,7 @@ public final class HpackTest { } @Test public void lowercaseHeaderNameBeforeEmit() throws IOException { - hpackWriter.writeHeaders(Arrays.asList(new Header("FoO", "BaR"))); + hpackWriter.writeHeaders(asList(new Header("FoO", "BaR"))); assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'B', 'a', 'R'); } @@ -872,26 +873,26 @@ public final class HpackTest { @Test public void emitsDynamicTableSizeUpdate() throws IOException { hpackWriter.setHeaderTableSizeSetting(2048); - hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); + hpackWriter.writeHeaders(asList(new Header("foo", "bar"))); assertBytes( 0x3F, 0xE1, 0xF, // Dynamic table size update (size = 2048). 0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r'); hpackWriter.setHeaderTableSizeSetting(8192); - hpackWriter.writeHeaders(Arrays.asList(new Header("bar", "foo"))); + hpackWriter.writeHeaders(asList(new Header("bar", "foo"))); assertBytes( 0x3F, 0xE1, 0x3F, // Dynamic table size update (size = 8192). 0x40, 3, 'b', 'a', 'r', 3, 'f', 'o', 'o'); // No more dynamic table updates should be emitted. - hpackWriter.writeHeaders(Arrays.asList(new Header("far", "boo"))); + hpackWriter.writeHeaders(asList(new Header("far", "boo"))); assertBytes(0x40, 3, 'f', 'a', 'r', 3, 'b', 'o', 'o'); } @Test public void noDynamicTableSizeUpdateWhenSizeIsEqual() throws IOException { int currentSize = hpackWriter.headerTableSizeSetting; hpackWriter.setHeaderTableSizeSetting(currentSize); - hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); + hpackWriter.writeHeaders(asList(new Header("foo", "bar"))); assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r'); } @@ -899,7 +900,7 @@ public final class HpackTest { @Test public void growDynamicTableSize() throws IOException { hpackWriter.setHeaderTableSizeSetting(8192); hpackWriter.setHeaderTableSizeSetting(16384); - hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); + hpackWriter.writeHeaders(asList(new Header("foo", "bar"))); assertBytes( 0x3F, 0xE1, 0x7F, // Dynamic table size update (size = 16384). @@ -909,7 +910,7 @@ public final class HpackTest { @Test public void shrinkDynamicTableSize() throws IOException { hpackWriter.setHeaderTableSizeSetting(2048); hpackWriter.setHeaderTableSizeSetting(0); - hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); + hpackWriter.writeHeaders(asList(new Header("foo", "bar"))); assertBytes( 0x20, // Dynamic size update (size = 0). @@ -922,7 +923,7 @@ public final class HpackTest { hpackWriter.setHeaderTableSizeSetting(0); hpackWriter.setHeaderTableSizeSetting(4096); hpackWriter.setHeaderTableSizeSetting(2048); - hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); + hpackWriter.writeHeaders(asList(new Header("foo", "bar"))); assertBytes( 0x20, // Dynamic size update (size = 0). 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 fd1703404..03b1e1eb4 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2ConnectionTest.java @@ -44,6 +44,7 @@ import org.junit.rules.TestRule; import org.junit.rules.Timeout; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.repeat; import static okhttp3.internal.Internal.initializeInstanceForTests; @@ -330,9 +331,9 @@ public final class Http2ConnectionTest { assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); } // connection - assertThat(windowUpdateStreamIds.contains(0)).isTrue(); + assertThat(windowUpdateStreamIds).contains(0); // stream - assertThat(windowUpdateStreamIds.contains(3)).isTrue(); + assertThat(windowUpdateStreamIds).contains(3); } } @@ -414,14 +415,14 @@ public final class Http2ConnectionTest { peer.acceptFrame(); // ACK peer.acceptFrame(); // SYN_STREAM peer.sendFrame().headers(false, 3, headerEntries("a", "android")); - final List
expectedRequestHeaders = Arrays.asList( + final List
expectedRequestHeaders = asList( new Header(Header.TARGET_METHOD, "GET"), new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_PATH, "/cached") ); peer.sendFrame().pushPromise(3, 2, expectedRequestHeaders); - final List
expectedResponseHeaders = Arrays.asList( + final List
expectedResponseHeaders = asList( new Header(Header.RESPONSE_STATUS, "200") ); peer.sendFrame().headers(true, 2, expectedResponseHeaders); @@ -465,13 +466,13 @@ public final class Http2ConnectionTest { // write the mocking script peer.sendFrame().settings(new Settings()); peer.acceptFrame(); // ACK - peer.sendFrame().pushPromise(3, 2, Arrays.asList( + peer.sendFrame().pushPromise(3, 2, asList( new Header(Header.TARGET_METHOD, "GET"), new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_PATH, "/cached") )); - peer.sendFrame().headers(true, 2, Arrays.asList( + peer.sendFrame().headers(true, 2, asList( new Header(Header.RESPONSE_STATUS, "200") )); peer.acceptFrame(); // RST_STREAM @@ -830,8 +831,8 @@ public final class Http2ConnectionTest { long pingAtNanos = System.nanoTime(); connection.writePingAndAwaitPong(); long elapsedNanos = System.nanoTime() - pingAtNanos; - assertThat(elapsedNanos > 0).isTrue(); - assertThat(elapsedNanos < TimeUnit.SECONDS.toNanos(1)).isTrue(); + assertThat(elapsedNanos).isGreaterThan(0L); + assertThat(elapsedNanos).isLessThan(TimeUnit.SECONDS.toNanos(1)); // verify the peer received what was expected InFrame pingFrame = peer.takeFrame(); @@ -1660,9 +1661,9 @@ public final class Http2ConnectionTest { assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); } // connection - assertThat(windowUpdateStreamIds.contains(0)).isTrue(); + assertThat(windowUpdateStreamIds).contains(0); // stream - assertThat(windowUpdateStreamIds.contains(3)).isTrue(); + assertThat(windowUpdateStreamIds).contains(3); } } 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 0854370aa..bce4c3485 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/Http2Test.java @@ -28,6 +28,7 @@ import okio.GzipSink; import okio.Okio; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.headerEntries; import static okhttp3.internal.http2.Http2.FLAG_COMPRESSED; import static okhttp3.internal.http2.Http2.FLAG_END_HEADERS; @@ -145,7 +146,7 @@ public final class Http2Test { @Test public void pushPromise() throws IOException { final int expectedPromisedStreamId = 11; - final List
pushPromise = Arrays.asList( + final List
pushPromise = asList( new Header(Header.TARGET_METHOD, "GET"), new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_AUTHORITY, "squareup.com"), 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 e4072033d..c4777c424 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/http2/HttpOverHttp2Test.java @@ -65,8 +65,8 @@ 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.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; @@ -78,13 +78,14 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; 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.api.Assertions.assertThat; 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.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; @@ -96,7 +97,7 @@ public final class HttpOverHttp2Test { @Parameters(name = "{0}") public static Collection data() { - return Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_2); + return asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_2); } @Rule public final TemporaryFolder tempDir = new TemporaryFolder(); @@ -119,13 +120,13 @@ public final class HttpOverHttp2Test { private OkHttpClient buildH2PriorKnowledgeClient() { return clientTestRule.client.newBuilder() - .protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)) + .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE)) .build(); } private OkHttpClient buildHttp2Client() { return clientTestRule.client.newBuilder() - .protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)) + .protocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1)) .sslSocketFactory( handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()) .hostnameVerifier(new RecordingHostnameVerifier()) @@ -134,7 +135,7 @@ public final class HttpOverHttp2Test { @Before public void setUp() { if (protocol == Protocol.H2_PRIOR_KNOWLEDGE) { - server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)); + server.setProtocols(asList(Protocol.H2_PRIOR_KNOWLEDGE)); } else { server.useHttps(handshakeCertificates.sslSocketFactory(), false); } @@ -162,15 +163,15 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.message()).isEqualTo(""); - Assertions.assertThat(response.protocol()).isEqualTo(protocol); + assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.message()).isEqualTo(""); + assertThat(response.protocol()).isEqualTo(protocol); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); - Assertions.assertThat(request.getHeader(":authority")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(request.getHeader(":scheme")).isEqualTo(scheme); + assertThat(request.getHeader(":authority")).isEqualTo( (server.getHostName() + ":" + server.getPort())); } @@ -182,7 +183,7 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().byteStream().read()).isEqualTo(-1); + assertThat(response.body().byteStream().read()).isEqualTo(-1); response.body().close(); } @@ -205,12 +206,12 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.body().string()).isEqualTo("ABCDE"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); assertArrayEquals(postBytes, request.getBody().readByteArray()); - Assertions.assertThat(request.getHeader("Content-Length")).isNull(); + assertThat(request.getHeader("Content-Length")).isNull(); } @Test public void userSuppliedContentLengthHeader() throws Exception { @@ -236,12 +237,12 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.body().string()).isEqualTo("ABCDE"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); assertArrayEquals(postBytes, request.getBody().readByteArray()); - Assertions.assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo( + assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo( (long) postBytes.length); } @@ -270,12 +271,12 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.body().string()).isEqualTo("ABCDE"); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); + assertThat(request.getRequestLine()).isEqualTo("POST /foo HTTP/1.1"); assertArrayEquals(postBytes, request.getBody().readByteArray()); - Assertions.assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo( + assertThat(Integer.parseInt(request.getHeader("Content-Length"))).isEqualTo( (long) postBytes.length); } @@ -292,12 +293,12 @@ public final class HttpOverHttp2Test { Response response1 = call1.execute(); Response response2 = call2.execute(); - 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); + assertThat(response1.body().source().readUtf8(3)).isEqualTo("ABC"); + assertThat(response2.body().source().readUtf8(3)).isEqualTo("GHI"); + assertThat(response1.body().source().readUtf8(3)).isEqualTo("DEF"); + assertThat(response2.body().source().readUtf8(3)).isEqualTo("JKL"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); response1.close(); response2.close(); @@ -319,14 +320,15 @@ 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(); - Assertions.assertThat(Util.discard(response1.body().source(), 1, TimeUnit.SECONDS)).overridingErrorMessage( - "Call should not have completed successfully.").isFalse(); + 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(); - Assertions.assertThat(response2.body().string()).isEqualTo("abc"); + assertThat(response2.body().string()).isEqualTo("abc"); } /** Wait for the client to receive {@code dataLength} DATA frames. */ @@ -363,7 +365,7 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("abc"); + assertThat(response2.body().string()).isEqualTo("abc"); } @Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception { @@ -379,10 +381,10 @@ public final class HttpOverHttp2Test { waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE); - Assertions.assertThat(response1.body().contentLength()).isEqualTo( + assertThat(response1.body().contentLength()).isEqualTo( (long) Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE); int read = response1.body().source().read(new byte[8192]); - Assertions.assertThat(read).isEqualTo(8192); + 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. @@ -390,13 +392,13 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.code()).isEqualTo(200); + assertThat(response2.code()).isEqualTo(200); // Close the response body. This should discard the buffered data and update the connection // flow-control window. response1.close(); - Assertions.assertThat(response2.body().string()).isEqualTo("abc"); + assertThat(response2.body().string()).isEqualTo("abc"); } /** https://github.com/square/okhttp/issues/373 */ @@ -409,8 +411,8 @@ public final class HttpOverHttp2Test { executor.execute(new AsyncRequest("/r1", countDownLatch)); executor.execute(new AsyncRequest("/r2", countDownLatch)); countDownLatch.await(); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void gzippedResponseBody() throws Exception { @@ -423,7 +425,7 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCABCABC"); + assertThat(response.body().string()).isEqualTo("ABCABCABC"); } @Test public void authenticate() throws Exception { @@ -443,13 +445,13 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("Successful auth!"); + assertThat(response.body().string()).isEqualTo("Successful auth!"); RecordedRequest denied = server.takeRequest(); - Assertions.assertThat(denied.getHeader("Authorization")).isNull(); + assertThat(denied.getHeader("Authorization")).isNull(); RecordedRequest accepted = server.takeRequest(); - Assertions.assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1"); - Assertions.assertThat(accepted.getHeader("Authorization")).isEqualTo(credential); + assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1"); + assertThat(accepted.getHeader("Authorization")).isEqualTo(credential); } @Test public void redirect() throws Exception { @@ -463,12 +465,12 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("This is the new location!"); + assertThat(response.body().string()).isEqualTo("This is the new location!"); RecordedRequest request1 = server.takeRequest(); - Assertions.assertThat(request1.getPath()).isEqualTo("/"); + assertThat(request1.getPath()).isEqualTo("/"); RecordedRequest request2 = server.takeRequest(); - Assertions.assertThat(request2.getPath()).isEqualTo("/foo"); + assertThat(request2.getPath()).isEqualTo("/foo"); } @Test public void readAfterLastByte() throws Exception { @@ -480,11 +482,11 @@ public final class HttpOverHttp2Test { Response response = call.execute(); InputStream in = response.body().byteStream(); - 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); + assertThat(in.read()).isEqualTo('A'); + assertThat(in.read()).isEqualTo('B'); + assertThat(in.read()).isEqualTo('C'); + assertThat(in.read()).isEqualTo(-1); + assertThat(in.read()).isEqualTo(-1); in.close(); } @@ -505,7 +507,7 @@ public final class HttpOverHttp2Test { call1.execute(); fail("Should have timed out!"); } catch (SocketTimeoutException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo("timeout"); + assertThat(expected.getMessage()).isEqualTo("timeout"); } // Confirm that a subsequent request on the same connection is not impacted. @@ -513,11 +515,11 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.body().string()).isEqualTo("A"); // Confirm that the connection was reused. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } /** @@ -540,7 +542,7 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo(new String(body)); + assertThat(response.body().string()).isEqualTo(new String(body)); } /** @@ -570,7 +572,7 @@ public final class HttpOverHttp2Test { response1.body().string(); fail("Should have timed out!"); } catch (SocketTimeoutException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo("timeout"); + assertThat(expected.getMessage()).isEqualTo("timeout"); } // Confirm that a subsequent request on the same connection is not impacted. @@ -578,11 +580,11 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo(body); + assertThat(response2.body().string()).isEqualTo(body); // Confirm that the connection was reused. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void connectionTimeout() throws Exception { @@ -607,7 +609,7 @@ public final class HttpOverHttp2Test { .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.body().string()).isEqualTo("A"); try { call2.execute(); @@ -616,8 +618,8 @@ public final class HttpOverHttp2Test { } // Confirm that the connection was reused. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void responsesAreCached() throws IOException { @@ -634,26 +636,26 @@ public final class HttpOverHttp2Test { .build()); Response response1 = call1.execute(); - 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); + assertThat(response1.body().string()).isEqualTo("A"); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.body().string()).isEqualTo("A"); Call call3 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response3 = call3.execute(); - Assertions.assertThat(response3.body().string()).isEqualTo("A"); + assertThat(response3.body().string()).isEqualTo("A"); - Assertions.assertThat(cache.requestCount()).isEqualTo(3); - Assertions.assertThat(cache.networkCount()).isEqualTo(1); - Assertions.assertThat(cache.hitCount()).isEqualTo(2); + assertThat(cache.requestCount()).isEqualTo(3); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(2); } @Test public void conditionalCache() throws IOException { @@ -671,21 +673,21 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.body().string()).isEqualTo("A"); + assertThat(response1.body().string()).isEqualTo("A"); - Assertions.assertThat(cache.requestCount()).isEqualTo(1); - Assertions.assertThat(cache.networkCount()).isEqualTo(1); - Assertions.assertThat(cache.hitCount()).isEqualTo(0); + assertThat(cache.requestCount()).isEqualTo(1); + assertThat(cache.networkCount()).isEqualTo(1); + assertThat(cache.hitCount()).isEqualTo(0); Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("A"); + assertThat(response2.body().string()).isEqualTo("A"); - Assertions.assertThat(cache.requestCount()).isEqualTo(2); - Assertions.assertThat(cache.networkCount()).isEqualTo(2); - Assertions.assertThat(cache.hitCount()).isEqualTo(1); + assertThat(cache.requestCount()).isEqualTo(2); + assertThat(cache.networkCount()).isEqualTo(2); + assertThat(cache.hitCount()).isEqualTo(1); } @Test public void responseCachedWithoutConsumingFullBody() throws IOException { @@ -704,14 +706,14 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.body().source().readUtf8(2)).isEqualTo("AB"); + 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(); - Assertions.assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD"); + assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD"); response2.body().close(); } @@ -732,10 +734,10 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo(""); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getHeader("Cookie")).isEqualTo("a=b"); + assertThat(request.getHeader("Cookie")).isEqualTo("a=b"); } @Test public void receiveResponseCookies() throws Exception { @@ -751,7 +753,7 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo(""); cookieJar.assertResponseCookies("a=b; path=/"); } @@ -770,13 +772,13 @@ public final class HttpOverHttp2Test { call1.cancel(); // That connection is pooled, and it works. - Assertions.assertThat(client.connectionPool().connectionCount()).isEqualTo(1); + assertThat(client.connectionPool().connectionCount()).isEqualTo(1); Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("def"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(response2.body().string()).isEqualTo("def"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Clean up the connection. response.close(); @@ -793,12 +795,12 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("abc"); + assertThat(response.body().string()).isEqualTo("abc"); // New connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Reused connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception { @@ -816,12 +818,12 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("abc"); + assertThat(response.body().string()).isEqualTo("abc"); // New connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // New connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception { @@ -842,14 +844,14 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("abc"); + assertThat(response.body().string()).isEqualTo("abc"); // New connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Reused connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); // New connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void recoverFromCancelReusesConnection() throws Exception { @@ -870,8 +872,8 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("def"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(response.body().string()).isEqualTo("def"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); } @Test public void recoverFromMultipleCancelReusesConnection() throws Exception { @@ -896,8 +898,8 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ghi"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); + assertThat(response.body().string()).isEqualTo("ghi"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } /** Make a call and canceling it as soon as it's accepted by the server. */ @@ -915,7 +917,7 @@ public final class HttpOverHttp2Test { fail(); } }); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo( + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo( (long) expectedSequenceNumber); call.cancel(); latch.await(); @@ -947,7 +949,7 @@ public final class HttpOverHttp2Test { call.execute(); fail(); } catch (StreamResetException expected) { - Assertions.assertThat(expected.errorCode).isEqualTo(errorCode); + assertThat(expected.errorCode).isEqualTo(errorCode); } } @@ -997,24 +999,24 @@ public final class HttpOverHttp2Test { .build(); blockingAuthClient.newCall(request).enqueue(callback); String response1 = responses.take(); - Assertions.assertThat(response1).isEqualTo(""); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(response1).isEqualTo(""); + 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(); - Assertions.assertThat(response2).isEqualTo("DEF"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(response2).isEqualTo("DEF"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + 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(); - Assertions.assertThat(response3).isEqualTo("ABC"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); + assertThat(response3).isEqualTo("ABC"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); } @Test public void nonAsciiResponseHeader() throws Exception { @@ -1028,8 +1030,8 @@ public final class HttpOverHttp2Test { Response response = call.execute(); response.close(); - Assertions.assertThat(response.header("Alpha")).isEqualTo("α"); - Assertions.assertThat(response.header("β")).isEqualTo("Beta"); + assertThat(response.header("Alpha")).isEqualTo("α"); + assertThat(response.header("β")).isEqualTo("Beta"); } @Test public void serverSendsPushPromise_GET() throws Exception { @@ -1045,20 +1047,20 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.message()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.message()).isEqualTo(""); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); - Assertions.assertThat(request.getHeader(":authority")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(request.getHeader(":scheme")).isEqualTo(scheme); + assertThat(request.getHeader(":authority")).isEqualTo( (server.getHostName() + ":" + server.getPort())); RecordedRequest pushedRequest = server.takeRequest(); - Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo( + assertThat(pushedRequest.getRequestLine()).isEqualTo( "GET /foo/bar HTTP/1.1"); - Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar"); + assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar"); } @Test public void serverSendsPushPromise_HEAD() throws Exception { @@ -1073,20 +1075,20 @@ public final class HttpOverHttp2Test { .url(server.url("/foo")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); - Assertions.assertThat(response.code()).isEqualTo(200); - Assertions.assertThat(response.message()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo("ABCDE"); + assertThat(response.code()).isEqualTo(200); + assertThat(response.message()).isEqualTo(""); RecordedRequest request = server.takeRequest(); - Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); - Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); - Assertions.assertThat(request.getHeader(":authority")).isEqualTo( + assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); + assertThat(request.getHeader(":scheme")).isEqualTo(scheme); + assertThat(request.getHeader(":authority")).isEqualTo( (server.getHostName() + ":" + server.getPort())); RecordedRequest pushedRequest = server.takeRequest(); - Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo( + assertThat(pushedRequest.getRequestLine()).isEqualTo( "HEAD /foo/bar HTTP/1.1"); - Assertions.assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar"); + assertThat(pushedRequest.getHeader("foo")).isEqualTo("bar"); } @Test public void noDataFramesSentWithNullRequestBody() throws Exception { @@ -1098,13 +1100,15 @@ public final class HttpOverHttp2Test { .method("DELETE", null) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); - Assertions.assertThat(response.protocol()).isEqualTo(protocol); + assertThat(response.protocol()).isEqualTo(protocol); List logs = http2Handler.takeAll(); - assertThat("header logged", firstFrame(logs, "HEADERS"), containsString("HEADERS END_STREAM|END_HEADERS")); + assertThat(firstFrame(logs, "HEADERS")) + .overridingErrorMessage("header logged") + .contains("HEADERS END_STREAM|END_HEADERS"); } @Test public void emptyDataFrameSentWithEmptyBody() throws Exception { @@ -1116,14 +1120,18 @@ public final class HttpOverHttp2Test { .method("DELETE", Util.EMPTY_REQUEST) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); - Assertions.assertThat(response.protocol()).isEqualTo(protocol); + assertThat(response.protocol()).isEqualTo(protocol); List logs = http2Handler.takeAll(); - assertThat("header logged", firstFrame(logs, "HEADERS"), containsString("HEADERS END_HEADERS")); - assertThat("data logged", firstFrame(logs, "DATA"), containsString("0 DATA END_STREAM")); + assertThat(firstFrame(logs, "HEADERS")) + .overridingErrorMessage("header logged") + .contains("HEADERS END_HEADERS"); + assertThat(firstFrame(logs, "DATA")) + .overridingErrorMessage("data logged") + .contains("0 DATA END_STREAM"); } @Test public void pingsTransmitted() throws Exception { @@ -1141,19 +1149,19 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); - Assertions.assertThat(response.protocol()).isEqualTo(protocol); + assertThat(response.protocol()).isEqualTo(protocol); // Confirm a single ping was sent and received, and its reply was sent and received. List logs = http2Handler.takeAll(); - Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( + assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( (long) 1); - Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo( + assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo( (long) 1); - Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")).isEqualTo( + assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")).isEqualTo( (long) 1); - Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( + assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( (long) 1); } @@ -1177,19 +1185,19 @@ public final class HttpOverHttp2Test { call.execute(); fail(); } catch (StreamResetException expected) { - Assertions.assertThat(expected.getMessage()).isEqualTo( + assertThat(expected.getMessage()).isEqualTo( "stream was reset: PROTOCOL_ERROR"); } long elapsedUntilFailure = System.nanoTime() - executeAtNanos; - Assertions.assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo( + assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo( (double) 1000, offset(250d)); // Confirm a single ping was sent but not acknowledged. List logs = http2Handler.takeAll(); - Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( + assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( (long) 1); - Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( + assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( (long) 0); } @@ -1227,7 +1235,7 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo(""); server.enqueue(new MockResponse() .setBody("ABC")); @@ -1251,17 +1259,17 @@ public final class HttpOverHttp2Test { .build()); Response response3 = call3.execute(); - Assertions.assertThat(response1.body().string()).isEqualTo("ABC"); - Assertions.assertThat(response2.body().string()).isEqualTo("DEF"); - Assertions.assertThat(response3.body().string()).isEqualTo("GHI"); + assertThat(response1.body().string()).isEqualTo("ABC"); + assertThat(response2.body().string()).isEqualTo("DEF"); + assertThat(response3.body().string()).isEqualTo("GHI"); // Settings connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); // Reuse settings connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); // Reuse settings connection. - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); // New connection! - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void connectionNotReusedAfterShutdown() throws Exception { @@ -1275,15 +1283,15 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response1 = call1.execute(); - Assertions.assertThat(response1.body().string()).isEqualTo("ABC"); + assertThat(response1.body().string()).isEqualTo("ABC"); Call call2 = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("DEF"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(response2.body().string()).isEqualTo("DEF"); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } /** @@ -1310,7 +1318,7 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("ABC"); + assertThat(response.body().string()).isEqualTo("ABC"); // Wait until the GOAWAY has been processed. RealConnection connection = (RealConnection) chain.connection(); while (connection.isHealthy(false)) ; @@ -1324,10 +1332,10 @@ public final class HttpOverHttp2Test { .url(server.url("/")) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("DEF"); + assertThat(response.body().string()).isEqualTo("DEF"); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); - Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); + assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); } @Test public void responseHeadersAfterGoaway() throws Exception { @@ -1350,9 +1358,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); - Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("DEF"); - Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC"); - Assertions.assertThat(server.getRequestCount()).isEqualTo(2); + assertThat(bodies.poll(2, SECONDS)).isEqualTo("DEF"); + assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC"); + assertThat(server.getRequestCount()).isEqualTo(2); } /** @@ -1394,7 +1402,7 @@ public final class HttpOverHttp2Test { .url("https://android.com/call2") .build()); Response response2 = call2.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("call2 response"); + assertThat(response2.body().string()).isEqualTo("call2 response"); } catch (IOException e) { throw new RuntimeException(e); } @@ -1420,27 +1428,27 @@ public final class HttpOverHttp2Test { .url("https://android.com/call1") .build()); Response response2 = call1.execute(); - Assertions.assertThat(response2.body().string()).isEqualTo("call1 response"); + assertThat(response2.body().string()).isEqualTo("call1 response"); RecordedRequest call1Connect = server.takeRequest(); - Assertions.assertThat(call1Connect.getMethod()).isEqualTo("CONNECT"); - Assertions.assertThat(call1Connect.getSequenceNumber()).isEqualTo(0); + assertThat(call1Connect.getMethod()).isEqualTo("CONNECT"); + assertThat(call1Connect.getSequenceNumber()).isEqualTo(0); RecordedRequest call2Connect = server.takeRequest(); - Assertions.assertThat(call2Connect.getMethod()).isEqualTo("CONNECT"); - Assertions.assertThat(call2Connect.getSequenceNumber()).isEqualTo(0); + assertThat(call2Connect.getMethod()).isEqualTo("CONNECT"); + assertThat(call2Connect.getSequenceNumber()).isEqualTo(0); RecordedRequest call2Get = server.takeRequest(); - Assertions.assertThat(call2Get.getMethod()).isEqualTo("GET"); - Assertions.assertThat(call2Get.getPath()).isEqualTo("/call2"); - Assertions.assertThat(call2Get.getSequenceNumber()).isEqualTo(0); + assertThat(call2Get.getMethod()).isEqualTo("GET"); + assertThat(call2Get.getPath()).isEqualTo("/call2"); + assertThat(call2Get.getSequenceNumber()).isEqualTo(0); RecordedRequest call1Get = server.takeRequest(); - Assertions.assertThat(call1Get.getMethod()).isEqualTo("GET"); - Assertions.assertThat(call1Get.getPath()).isEqualTo("/call1"); - Assertions.assertThat(call1Get.getSequenceNumber()).isEqualTo(1); + assertThat(call1Get.getMethod()).isEqualTo("GET"); + assertThat(call1Get.getPath()).isEqualTo("/call1"); + assertThat(call1Get.getSequenceNumber()).isEqualTo(1); - Assertions.assertThat(client.connectionPool().connectionCount()).isEqualTo(1); + assertThat(client.connectionPool().connectionCount()).isEqualTo(1); } /** https://github.com/square/okhttp/issues/3103 */ @@ -1463,10 +1471,10 @@ public final class HttpOverHttp2Test { .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo(""); + assertThat(response.body().string()).isEqualTo(""); RecordedRequest recordedRequest = server.takeRequest(); - Assertions.assertThat(recordedRequest.getHeader(":authority")).isEqualTo( + assertThat(recordedRequest.getHeader(":authority")).isEqualTo( "privateobject.com"); } @@ -1493,7 +1501,7 @@ public final class HttpOverHttp2Test { .url(server.url(path)) .build()); Response response = call.execute(); - Assertions.assertThat(response.body().string()).isEqualTo("A"); + 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/tls/ClientAuthTest.java b/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java index 252333bba..c65c4b56d 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/tls/ClientAuthTest.java @@ -42,6 +42,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.defaultClient; import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion; import static okhttp3.internal.platform.PlatformTest.getPlatform; @@ -281,7 +282,7 @@ public final class ClientAuthTest { X509KeyManager keyManager = newKeyManager( null, serverCert, serverIntermediateCa.certificate()); X509TrustManager trustManager = newTrustManager( - null, Arrays.asList(serverRootCa.certificate(), clientRootCa.certificate())); + null, asList(serverRootCa.certificate(), clientRootCa.certificate())); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, new SecureRandom()); 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 270357969..0eb5ff2cd 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketHttpTest.java @@ -21,8 +21,6 @@ import java.io.InterruptedIOException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.SocketTimeoutException; -import java.util.Arrays; -import java.util.Collections; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -50,6 +48,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.ensureAllConnectionsReleased; import static okhttp3.TestUtil.repeat; @@ -416,16 +415,16 @@ public final class WebSocketHttpTest { // Send messages until the client's outgoing buffer overflows! ByteString message = ByteString.of(new byte[1024 * 1024]); - int messageCount = 0; + long messageCount = 0; while (true) { boolean success = webSocket.send(message); if (!success) break; messageCount++; long queueSize = webSocket.queueSize(); - assertThat(queueSize >= 0 && queueSize <= messageCount * message.size()).isTrue(); + assertThat(queueSize).isBetween(0L, messageCount * message.size()); // Expect to fail before enqueueing 32 MiB. - assertThat(messageCount < 32).isTrue(); + assertThat(messageCount).isLessThan(32L); } // Confirm all sent messages were received, followed by a client-initiated close. @@ -744,7 +743,7 @@ public final class WebSocketHttpTest { @Test public void webSocketConnectionIsReleased() throws Exception { // This test assumes HTTP/1.1 pooling semantics. client = client.newBuilder() - .protocols(Arrays.asList(Protocol.HTTP_1_1)) + .protocols(asList(Protocol.HTTP_1_1)) .build(); webServer.enqueue(new MockResponse() 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 401f50926..07dac19eb 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketReaderTest.java @@ -19,7 +19,6 @@ import java.io.EOFException; import java.io.IOException; import java.net.ProtocolException; import java.util.Random; -import java.util.regex.Pattern; import okhttp3.internal.Util; import okio.Buffer; import okio.ByteString; @@ -309,9 +308,7 @@ public final class WebSocketReaderTest { clientReader.processNextFrame(); fail(); } catch (ProtocolException e) { - String message = e.getMessage(); - assertThat(Pattern.matches("Code \\d+ is reserved and may not be used.", message)).overridingErrorMessage( - message).isTrue(); + assertThat(e.getMessage()).matches("Code \\d+ is reserved and may not be used."); } } assertThat(count).isEqualTo(1991); 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 d46205c5f..0ab1d1857 100644 --- a/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java +++ b/okhttp-tests/src/test/java/okhttp3/internal/ws/WebSocketRecorder.java @@ -16,7 +16,6 @@ package okhttp3.internal.ws; import java.io.IOException; -import java.util.Arrays; import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -161,7 +160,7 @@ public final class WebSocketRecorder extends WebSocketListener { } public void assertExhausted() { - assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue(); + assertThat(events).isEmpty(); } public WebSocket assertOpen() { @@ -191,8 +190,7 @@ public final class WebSocketRecorder extends WebSocketListener { assertThat(failure.response).isNull(); assertThat(failure.t.getClass()).isEqualTo(cls); if (messages.length > 0) { - assertThat(Arrays.asList(messages).contains(failure.t.getMessage())).overridingErrorMessage( - failure.t.getMessage()).isTrue(); + assertThat(messages).contains(failure.t.getMessage()); } } diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java index ac5bc6a53..f36743f47 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java +++ b/okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.java @@ -37,6 +37,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import static java.util.Arrays.asList; import static okhttp3.internal.Util.closeQuietly; import static org.assertj.core.api.Assertions.assertThat; @@ -91,16 +92,16 @@ public final class HandshakeCertificatesTest { Future clientHandshakeFuture = doClientHandshake(client, serverAddress); Handshake serverHandshake = serverHandshakeFuture.get(); - assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo( - serverHandshake.peerCertificates()); - assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo( - serverHandshake.localCertificates()); + assertThat(asList(clientCertificate.certificate(), clientIntermediate.certificate())) + .isEqualTo(serverHandshake.peerCertificates()); + assertThat(asList(serverCertificate.certificate(), serverIntermediate.certificate())) + .isEqualTo(serverHandshake.localCertificates()); Handshake clientHandshake = clientHandshakeFuture.get(); - assertThat(Arrays.asList(serverCertificate.certificate(), serverIntermediate.certificate())).isEqualTo( - clientHandshake.peerCertificates()); - assertThat(Arrays.asList(clientCertificate.certificate(), clientIntermediate.certificate())).isEqualTo( - clientHandshake.localCertificates()); + assertThat(asList(serverCertificate.certificate(), serverIntermediate.certificate())) + .isEqualTo(clientHandshake.peerCertificates()); + assertThat(asList(clientCertificate.certificate(), clientIntermediate.certificate())) + .isEqualTo(clientHandshake.localCertificates()); } @Test public void keyManager() { @@ -120,8 +121,8 @@ public final class HandshakeCertificatesTest { .build(); assertPrivateKeysEquals(certificate.keyPair().getPrivate(), handshakeCertificates.keyManager().getPrivateKey("private")); - assertThat(Arrays.asList(handshakeCertificates.keyManager().getCertificateChain("private"))).isEqualTo( - Arrays.asList(certificate.certificate(), intermediate.certificate())); + assertThat(asList(handshakeCertificates.keyManager().getCertificateChain("private"))).isEqualTo( + asList(certificate.certificate(), intermediate.certificate())); } @Test public void platformTrustedCertificates() { @@ -135,7 +136,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. - assertThat(names.contains("CN=Entrust")).overridingErrorMessage(names.toString()).isTrue(); + assertThat(names).contains("CN=Entrust"); } private InetSocketAddress startTlsServer() throws IOException { diff --git a/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java b/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java index 4335d67f2..76dbeb81f 100644 --- a/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java +++ b/okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.java @@ -23,14 +23,12 @@ import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import java.util.concurrent.TimeUnit; import okio.ByteString; import org.bouncycastle.asn1.x509.GeneralName; import org.junit.Test; +import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.Offset.offset; @@ -42,7 +40,7 @@ public final class HeldCertificateTest { X509Certificate certificate = heldCertificate.certificate(); assertThat(certificate.getSubjectX500Principal().getName()).overridingErrorMessage( "self-signed").isEqualTo(certificate.getIssuerX500Principal().getName()); - assertThat(certificate.getIssuerX500Principal().getName().matches("CN=[0-9a-f-]{36}")).isTrue(); + assertThat(certificate.getIssuerX500Principal().getName()).matches("CN=[0-9a-f-]{36}"); assertThat(certificate.getSerialNumber()).isEqualTo(BigInteger.ONE); assertThat(certificate.getSubjectAlternativeNames()).isNull(); @@ -87,11 +85,9 @@ public final class HeldCertificateTest { .build(); X509Certificate certificate = heldCertificate.certificate(); - List> subjectAlternativeNames = new ArrayList<>( - certificate.getSubjectAlternativeNames()); - assertThat(Arrays.asList( - Arrays.asList(GeneralName.iPAddress, "1.1.1.1"), - Arrays.asList(GeneralName.dNSName, "cash.app"))).isEqualTo(subjectAlternativeNames); + assertThat(certificate.getSubjectAlternativeNames()).containsExactly( + asList(GeneralName.iPAddress, "1.1.1.1"), + asList(GeneralName.dNSName, "cash.app")); } @Test public void commonName() { diff --git a/okhttp/src/main/java/okhttp3/CertificatePinner.java b/okhttp/src/main/java/okhttp3/CertificatePinner.java index 474c245ae..ba4470458 100644 --- a/okhttp/src/main/java/okhttp3/CertificatePinner.java +++ b/okhttp/src/main/java/okhttp3/CertificatePinner.java @@ -18,7 +18,6 @@ package okhttp3; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; @@ -29,6 +28,8 @@ import javax.net.ssl.SSLPeerUnverifiedException; import okhttp3.internal.tls.CertificateChainCleaner; import okio.ByteString; +import static java.util.Arrays.asList; + /** * Constrains which certificates are trusted. Pinning certificates defends against attacks on * certificate authorities. It also prevents connections through man-in-the-middle certificate @@ -207,7 +208,7 @@ public final class CertificatePinner { /** @deprecated replaced with {@link #check(String, List)}. */ public void check(String hostname, Certificate... peerCertificates) throws SSLPeerUnverifiedException { - check(hostname, Arrays.asList(peerCertificates)); + check(hostname, asList(peerCertificates)); } /** diff --git a/okhttp/src/main/java/okhttp3/Dns.java b/okhttp/src/main/java/okhttp3/Dns.java index feba0db7c..38d110c24 100644 --- a/okhttp/src/main/java/okhttp3/Dns.java +++ b/okhttp/src/main/java/okhttp3/Dns.java @@ -17,9 +17,10 @@ package okhttp3; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.Arrays; import java.util.List; +import static java.util.Arrays.asList; + /** * A domain name service that resolves IP addresses for host names. Most applications will use the * {@linkplain #SYSTEM system DNS service}, which is the default. Some applications may provide @@ -36,7 +37,7 @@ public interface Dns { Dns SYSTEM = hostname -> { if (hostname == null) throw new UnknownHostException("hostname == null"); try { - return Arrays.asList(InetAddress.getAllByName(hostname)); + return asList(InetAddress.getAllByName(hostname)); } catch (NullPointerException e) { UnknownHostException unknownHostException = new UnknownHostException("Broken system behaviour for dns lookup of " + hostname); diff --git a/okhttp/src/main/java/okhttp3/internal/Util.java b/okhttp/src/main/java/okhttp3/internal/Util.java index 3e1a2ba76..0dec728da 100644 --- a/okhttp/src/main/java/okhttp3/internal/Util.java +++ b/okhttp/src/main/java/okhttp3/internal/Util.java @@ -59,6 +59,7 @@ import okio.Source; import static java.nio.charset.StandardCharsets.UTF_16BE; import static java.nio.charset.StandardCharsets.UTF_16LE; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.Arrays.asList; /** Junk drawer of utility methods. */ public final class Util { @@ -231,7 +232,7 @@ public final class Util { /** Returns an immutable list containing {@code elements}. */ @SafeVarargs public static List immutableList(T... elements) { - return Collections.unmodifiableList(Arrays.asList(elements.clone())); + return Collections.unmodifiableList(asList(elements.clone())); } public static ThreadFactory threadFactory(String name, boolean daemon) { diff --git a/samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java b/samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java index b568bdf01..228956ec1 100644 --- a/samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java +++ b/samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java @@ -37,6 +37,8 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +import static java.util.Arrays.asList; + public final class CustomCipherSuites { private final OkHttpClient client; @@ -45,7 +47,7 @@ public final class CustomCipherSuites { // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should // not customize the cipher suites list. - List customCipherSuites = Arrays.asList( + List customCipherSuites = asList( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,