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

Use more AssertJ features

This commit is contained in:
Jesse Wilson
2019-03-13 22:35:04 -04:00
parent 8aa1e51789
commit dedc6ecd5b
49 changed files with 1140 additions and 1211 deletions

View File

@ -28,7 +28,6 @@ import java.net.SocketTimeoutException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -38,7 +37,6 @@ import okhttp3.Headers;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.Protocol; import okhttp3.Protocol;
import okhttp3.RecordingHostnameVerifier; import okhttp3.RecordingHostnameVerifier;
import okhttp3.internal.Util;
import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import org.junit.After; import org.junit.After;
@ -48,6 +46,7 @@ import org.junit.runner.Description;
import org.junit.runners.model.Statement; import org.junit.runners.model.Statement;
import static java.nio.charset.StandardCharsets.UTF_8; 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.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
@ -248,11 +247,7 @@ public final class MockWebServerTest {
assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1);
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertThat(elapsedMillis).isBetween(500L, 1000L);
assertThat(elapsedMillis >= 500).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
assertThat(elapsedMillis < 1000).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
} }
/** /**
@ -276,11 +271,7 @@ public final class MockWebServerTest {
assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1);
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertThat(elapsedMillis).isBetween(500L, 1000L);
assertThat(elapsedMillis >= 500).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
assertThat(elapsedMillis < 1000).overridingErrorMessage(
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
} }
/** Delay the response body by sleeping 1s. */ /** Delay the response body by sleeping 1s. */
@ -295,8 +286,7 @@ public final class MockWebServerTest {
assertThat(in.read()).isEqualTo('A'); assertThat(in.read()).isEqualTo('A');
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos);
assertThat(elapsedMillis >= 1000).overridingErrorMessage( assertThat(elapsedMillis).isGreaterThanOrEqualTo(1000L);
Util.format("Request + Response: %sms", elapsedMillis)).isTrue();
in.close(); in.close();
} }
@ -382,7 +372,7 @@ public final class MockWebServerTest {
} }
@Test public void portImplicitlyStarts() throws IOException { @Test public void portImplicitlyStarts() throws IOException {
assertThat(server.getPort() > 0).isTrue(); assertThat(server.getPort()).isGreaterThan(0);
} }
@Test public void hostnameImplicitlyStarts() throws IOException { @Test public void hostnameImplicitlyStarts() throws IOException {
@ -468,7 +458,7 @@ public final class MockWebServerTest {
refusedConnection.getResponseCode(); refusedConnection.getResponseCode();
fail("Second connection should be refused"); fail("Second connection should be refused");
} catch (ConnectException e ) { } catch (ConnectException e ) {
assertThat(e.getMessage().contains("refused")).isTrue(); assertThat(e.getMessage()).contains("refused");
} }
} }
@ -491,7 +481,7 @@ public final class MockWebServerTest {
@Test public void testH2PriorKnowledgeServerFallback() { @Test public void testH2PriorKnowledgeServerFallback() {
try { 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(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo( assertThat(expected.getMessage()).isEqualTo(
@ -503,7 +493,7 @@ public final class MockWebServerTest {
@Test public void testH2PriorKnowledgeServerDuplicates() { @Test public void testH2PriorKnowledgeServerDuplicates() {
try { try {
// Treating this use case as user error // 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(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo( assertThat(expected.getMessage()).isEqualTo(
@ -513,7 +503,7 @@ public final class MockWebServerTest {
} }
@Test public void testMockWebServerH2PriorKnowledgeProtocol() { @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().size()).isEqualTo(1);
assertThat(server.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE); assertThat(server.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);

View File

@ -39,6 +39,7 @@ import okio.BufferedSink;
import okio.Okio; import okio.Okio;
import okio.Source; import okio.Source;
import static java.util.Arrays.asList;
import static okhttp3.internal.platform.Platform.INFO; import static okhttp3.internal.platform.Platform.INFO;
import static okhttp3.tls.internal.TlsUtil.localhost; 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 { private void send404(Http2Stream stream, String path) throws IOException {
List<Header> responseHeaders = Arrays.asList( List<Header> responseHeaders = asList(
new Header(":status", "404"), new Header(":status", "404"),
new Header(":version", "HTTP/1.1"), new Header(":version", "HTTP/1.1"),
new Header("content-type", "text/plain") 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 { private void serveDirectory(Http2Stream stream, File[] files) throws IOException {
List<Header> responseHeaders = Arrays.asList( List<Header> responseHeaders = asList(
new Header(":status", "200"), new Header(":status", "200"),
new Header(":version", "HTTP/1.1"), new Header(":version", "HTTP/1.1"),
new Header("content-type", "text/html; charset=UTF-8") 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 { private void serveFile(Http2Stream stream, File file) throws IOException {
List<Header> responseHeaders = Arrays.asList( List<Header> responseHeaders = asList(
new Header(":status", "200"), new Header(":status", "200"),
new Header(":version", "HTTP/1.1"), new Header(":version", "HTTP/1.1"),
new Header("content-type", contentType(file)) new Header("content-type", contentType(file))

View File

@ -19,7 +19,6 @@ import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -40,6 +39,8 @@ import okhttp3.internal.platform.Platform;
import okhttp3.internal.publicsuffix.PublicSuffixDatabase; import okhttp3.internal.publicsuffix.PublicSuffixDatabase;
import okio.ByteString; import okio.ByteString;
import static java.util.Arrays.asList;
/** /**
* DNS over HTTPS implementation. * DNS over HTTPS implementation.
* *
@ -348,7 +349,7 @@ public class DnsOverHttps implements Dns {
} }
public Builder bootstrapDnsHosts(InetAddress... bootstrapDnsHosts) { public Builder bootstrapDnsHosts(InetAddress... bootstrapDnsHosts) {
return bootstrapDnsHosts(Arrays.asList(bootstrapDnsHosts)); return bootstrapDnsHosts(asList(bootstrapDnsHosts));
} }
public Builder systemDns(Dns systemDns) { public Builder systemDns(Dns systemDns) {

View File

@ -20,8 +20,6 @@ import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import okhttp3.Cache; import okhttp3.Cache;
import okhttp3.Dns; import okhttp3.Dns;
@ -84,8 +82,8 @@ public class DnsOverHttpsTest {
List<InetAddress> result = dns.lookup("google.com"); List<InetAddress> result = dns.lookup("google.com");
assertThat(result.size()).isEqualTo(2); assertThat(result.size()).isEqualTo(2);
assertThat(result.contains(address("157.240.1.18"))).isTrue(); assertThat(result).contains(address("157.240.1.18"));
assertThat(result.contains(address("2a03:2880:f029:11:face:b00c:0:2"))).isTrue(); assertThat(result).contains(address("2a03:2880:f029:11:face:b00c:0:2"));
RecordedRequest request1 = server.takeRequest(); RecordedRequest request1 = server.takeRequest();
assertThat(request1.getMethod()).isEqualTo("GET"); assertThat(request1.getMethod()).isEqualTo("GET");
@ -93,10 +91,9 @@ public class DnsOverHttpsTest {
RecordedRequest request2 = server.takeRequest(); RecordedRequest request2 = server.takeRequest();
assertThat(request2.getMethod()).isEqualTo("GET"); assertThat(request2.getMethod()).isEqualTo("GET");
assertThat(new LinkedHashSet<>(Arrays.asList(request1.getPath(), request2.getPath()))).isEqualTo( assertThat(asList(request1.getPath(), request2.getPath())).containsExactlyInAnyOrder(
new HashSet<>( "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ",
Arrays.asList("/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ", "/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ");
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ")));
} }
@Test public void failure() throws Exception { @Test public void failure() throws Exception {
@ -130,9 +127,8 @@ public class DnsOverHttpsTest {
} catch (IOException ioe) { } catch (IOException ioe) {
assertThat(ioe.getMessage()).isEqualTo("google.com"); assertThat(ioe.getMessage()).isEqualTo("google.com");
Throwable cause = ioe.getCause(); Throwable cause = ioe.getCause();
assertThat(cause instanceof IOException).isTrue(); assertThat(cause).isInstanceOf(IOException.class);
assertThat(cause.getMessage()).isEqualTo( assertThat(cause).hasMessage("response size exceeds limit (65536 bytes): 65537 bytes");
"response size exceeds limit (65536 bytes): 65537 bytes");
} }
} }
@ -143,10 +139,8 @@ public class DnsOverHttpsTest {
dns.lookup("google.com"); dns.lookup("google.com");
fail(); fail();
} catch (IOException ioe) { } catch (IOException ioe) {
assertThat(ioe.getMessage()).isEqualTo("google.com"); assertThat(ioe).hasMessage("google.com");
Throwable cause = ioe.getCause(); assertThat(ioe.getCause()).isInstanceOf(RuntimeException.class);
boolean condition = cause instanceof RuntimeException;
assertThat(condition).isTrue();
} }
} }

View File

@ -27,13 +27,15 @@ import okhttp3.Cache;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import static java.util.Arrays.asList;
public class TestDohMain { public class TestDohMain {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
Security.insertProviderAt(new org.conscrypt.OpenSSLProvider(), 1); Security.insertProviderAt(new org.conscrypt.OpenSSLProvider(), 1);
OkHttpClient bootstrapClient = new OkHttpClient.Builder().build(); OkHttpClient bootstrapClient = new OkHttpClient.Builder().build();
List<String> names = Arrays.asList("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee"); List<String> names = asList("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee");
try { try {
System.out.println("uncached\n********\n"); System.out.println("uncached\n********\n");
@ -53,7 +55,7 @@ public class TestDohMain {
runBatch(badProviders, names); runBatch(badProviders, names);
System.out.println("cached first run\n****************\n"); 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(); bootstrapClient = bootstrapClient.newBuilder().cache(dnsCache).build();
dnsProviders = DohProviders.providers(bootstrapClient, true, true, true); dnsProviders = DohProviders.providers(bootstrapClient, true, true, true);
runBatch(dnsProviders, names); runBatch(dnsProviders, names);

View File

@ -26,6 +26,8 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import okio.Okio; import okio.Okio;
import static java.util.Arrays.asList;
/** /**
* Utilities for reading HPACK tests. * Utilities for reading HPACK tests.
*/ */
@ -51,7 +53,7 @@ public final class HpackJsonUtil {
File testCaseDirectory = new File(HpackJsonUtil.class.getResource("/hpack-test-case").toURI()); File testCaseDirectory = new File(HpackJsonUtil.class.getResource("/hpack-test-case").toURI());
List<String> storyNames = new ArrayList<>(); List<String> storyNames = new ArrayList<>();
for (File path : testCaseDirectory.listFiles()) { 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 { try {
Story firstStory = readStory(new File(path, "story_00.json")); Story firstStory = readStory(new File(path, "story_00.json"));
if (firstStory.getDraft() >= BASE_DRAFT) { if (firstStory.getDraft() >= BASE_DRAFT) {

View File

@ -19,7 +19,6 @@ import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import okhttp3.HttpUrl; import okhttp3.HttpUrl;
@ -846,17 +845,16 @@ public final class HttpLoggingInterceptorTest {
private int index; private int index;
LogRecorder assertLogEqual(String expected) { 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++); String actual = logs.get(index++);
assertThat(actual).isEqualTo(expected); assertThat(actual).isEqualTo(expected);
return this; return this;
} }
LogRecorder assertLogMatch(String pattern) { 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++); String actual = logs.get(index++);
assertThat(Pattern.matches(pattern, actual)).overridingErrorMessage( assertThat(actual).matches(pattern);
"<" + actual + "> did not match pattern <" + pattern + ">").isTrue();
return this; return this;
} }

View File

@ -19,10 +19,10 @@ import java.io.IOException;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.Response; import okhttp3.Response;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -65,7 +65,7 @@ public final class EventSourceRecorder extends EventSourceListener {
} }
public void assertExhausted() { 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) { public void assertEvent(@Nullable String id, @Nullable String type, String data) {

View File

@ -30,9 +30,9 @@ public final class ServerSentEventIteratorTest {
private final Deque<Object> callbacks = new ArrayDeque<>(); private final Deque<Object> callbacks = new ArrayDeque<>();
@After public void after() { @After public void after() {
assertThat(callbacks.isEmpty()).overridingErrorMessage("Unconsumed events: " + callbacks).isTrue(); assertThat(callbacks).isEmpty();
} }
@Test public void multiline() throws IOException { @Test public void multiline() throws IOException {
consumeEvents("" consumeEvents(""
+ "data: YHOO\n" + "data: YHOO\n"
@ -177,7 +177,7 @@ public final class ServerSentEventIteratorTest {
+ "\n"); + "\n");
assertThat(callbacks.remove()).isEqualTo(22L); assertThat(callbacks.remove()).isEqualTo(22L);
} }
private void consumeEvents(String source) throws IOException { private void consumeEvents(String source) throws IOException {
ServerSentEventReader.Callback callback = new ServerSentEventReader.Callback() { ServerSentEventReader.Callback callback = new ServerSentEventReader.Callback() {
@Override public void onEvent(@Nullable String id, @Nullable String type, String data) { @Override public void onEvent(@Nullable String id, @Nullable String type, String data) {

View File

@ -17,11 +17,11 @@ package okhttp3;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Deque; import java.util.Deque;
import java.util.List; import java.util.List;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public final class RecordingCookieJar implements CookieJar { public final class RecordingCookieJar implements CookieJar {
@ -29,7 +29,7 @@ public final class RecordingCookieJar implements CookieJar {
private final Deque<List<Cookie>> responseCookies = new ArrayDeque<>(); private final Deque<List<Cookie>> responseCookies = new ArrayDeque<>();
public void enqueueRequestCookies(Cookie... cookies) { public void enqueueRequestCookies(Cookie... cookies) {
requestCookies.add(Arrays.asList(cookies)); requestCookies.add(asList(cookies));
} }
public List<Cookie> takeResponseCookies() { public List<Cookie> takeResponseCookies() {

View File

@ -2,11 +2,12 @@ package okhttp3;
import java.io.IOException; import java.io.IOException;
import java.security.Security; import java.security.Security;
import java.util.Arrays;
import java.util.List; import java.util.List;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
import org.conscrypt.Conscrypt; import org.conscrypt.Conscrypt;
import static java.util.Arrays.asList;
public class TestTls13Request { public class TestTls13Request {
// TLS 1.3 // TLS 1.3
@ -45,7 +46,7 @@ public class TestTls13Request {
// https://github.com/tlswg/tls13-spec/wiki/Implementations // https://github.com/tlswg/tls13-spec/wiki/Implementations
List<String> urls = List<String> 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.cloudflare.com", "https://www.allizom.org/robots.txt",
"https://tls13.crypto.mozilla.org/", "https://tls.ctf.network/robots.txt", "https://tls13.crypto.mozilla.org/", "https://tls.ctf.network/robots.txt",
"https://rustls.jbp.io/", "https://h2o.examp1e.net", "https://mew.org/", "https://rustls.jbp.io/", "https://h2o.examp1e.net", "https://mew.org/",
@ -75,7 +76,7 @@ public class TestTls13Request {
} }
private static OkHttpClient buildClient(ConnectionSpec... specs) { 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) { private static void sendRequest(OkHttpClient client, String url) {

View File

@ -62,7 +62,6 @@ import okhttp3.RecordingEventListener.ConnectionReleased;
import okhttp3.RecordingEventListener.ResponseFailed; import okhttp3.RecordingEventListener.ResponseFailed;
import okhttp3.internal.DoubleInetAddressDns; import okhttp3.internal.DoubleInetAddressDns;
import okhttp3.internal.RecordingOkAuthenticator; import okhttp3.internal.RecordingOkAuthenticator;
import okhttp3.internal.Util;
import okhttp3.internal.Version; import okhttp3.internal.Version;
import okhttp3.internal.http.RecordingProxySelector; import okhttp3.internal.http.RecordingProxySelector;
import okhttp3.internal.io.InMemoryFileSystem; import okhttp3.internal.io.InMemoryFileSystem;
@ -88,6 +87,7 @@ import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; 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.CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256;
import static okhttp3.TestUtil.awaitGarbageCollection; import static okhttp3.TestUtil.awaitGarbageCollection;
import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion; import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion;
@ -205,8 +205,7 @@ public final class CallTest {
.assertHeader("B", "123", "234"); .assertHeader("B", "123", "234");
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getHeaders().values("A")).isEqualTo( assertThat(recordedRequest.getHeaders().values("A")).containsExactly("345", "456");
Arrays.asList("345", "456"));
} }
@Test public void repeatedHeaderNames_HTTP_2() throws Exception { @Test public void repeatedHeaderNames_HTTP_2() throws Exception {
@ -724,8 +723,8 @@ public final class CallTest {
bodies.add(firstResponse.getBody()); bodies.add(firstResponse.getBody());
bodies.add(secondResponse.getBody()); bodies.add(secondResponse.getBody());
assertThat(bodies.contains("abc")).isTrue(); assertThat(bodies).contains("abc");
assertThat(bodies.contains("def")).isTrue(); assertThat(bodies).contains("def");
} }
@Test public void get_Async() throws Exception { @Test public void get_Async() throws Exception {
@ -857,8 +856,7 @@ public final class CallTest {
// Timed out as expected. // Timed out as expected.
long elapsedNanos = System.nanoTime() - startNanos; long elapsedNanos = System.nanoTime() - startNanos;
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos); long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos);
assertThat(elapsedMillis < 500).overridingErrorMessage( assertThat(elapsedMillis).isLessThan(500);
Util.format("Timed out: %sms", elapsedMillis)).isTrue();
} finally { } finally {
bodySource.close(); bodySource.close();
} }
@ -1102,7 +1100,7 @@ public final class CallTest {
SSLProtocolException.class, // RI response to the FAIL_HANDSHAKE SSLProtocolException.class, // RI response to the FAIL_HANDSHAKE
SSLHandshakeException.class // Android's 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 { @Test public void recoverFromTlsHandshakeFailure() throws Exception {
@ -1113,7 +1111,7 @@ public final class CallTest {
client = client.newBuilder() client = client.newBuilder()
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // 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( .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
@ -1124,7 +1122,7 @@ public final class CallTest {
@Test public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception { @Test public void recoverFromTlsHandshakeFailure_tlsFallbackScsvEnabled() throws Exception {
final String tlsFallbackScsv = "TLS_FALLBACK_SCSV"; final String tlsFallbackScsv = "TLS_FALLBACK_SCSV";
List<String> supportedCiphers = List<String> supportedCiphers =
Arrays.asList(handshakeCertificates.sslSocketFactory().getSupportedCipherSuites()); asList(handshakeCertificates.sslSocketFactory().getSupportedCipherSuites());
if (!supportedCiphers.contains(tlsFallbackScsv)) { if (!supportedCiphers.contains(tlsFallbackScsv)) {
// This only works if the client socket supports TLS_FALLBACK_SCSV. // This only works if the client socket supports TLS_FALLBACK_SCSV.
return; return;
@ -1138,7 +1136,7 @@ public final class CallTest {
client = client.newBuilder() client = client.newBuilder()
.sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager()) .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // 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()) .hostnameVerifier(new RecordingHostnameVerifier())
.build(); .build();
@ -1151,9 +1149,9 @@ public final class CallTest {
List<SSLSocket> clientSockets = clientSocketFactory.getSocketsCreated(); List<SSLSocket> clientSockets = clientSocketFactory.getSocketsCreated();
SSLSocket firstSocket = clientSockets.get(0); SSLSocket firstSocket = clientSockets.get(0);
assertThat(Arrays.asList(firstSocket.getEnabledCipherSuites()).contains(tlsFallbackScsv)).isFalse(); assertThat(asList(firstSocket.getEnabledCipherSuites())).doesNotContain(tlsFallbackScsv);
SSLSocket secondSocket = clientSockets.get(1); 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 { @Test public void recoverFromTlsHandshakeFailure_Async() throws Exception {
@ -1164,7 +1162,7 @@ public final class CallTest {
client = client.newBuilder() client = client.newBuilder()
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
// Attempt RESTRICTED_TLS then fall back to MODERN_TLS. // 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( .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
.build(); .build();
@ -1179,7 +1177,7 @@ public final class CallTest {
@Test public void noRecoveryFromTlsHandshakeFailureWhenTlsFallbackIsDisabled() throws Exception { @Test public void noRecoveryFromTlsHandshakeFailureWhenTlsFallbackIsDisabled() throws Exception {
client = client.newBuilder() client = client.newBuilder()
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)) .connectionSpecs(asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT))
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.sslSocketFactory( .sslSocketFactory(
suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager()) suppressTlsFallbackClientSocketFactory(), handshakeCertificates.trustManager())
@ -1247,7 +1245,7 @@ public final class CallTest {
.sslSocketFactory( .sslSocketFactory(
socketFactoryWithCipherSuite(clientCertificates.sslSocketFactory(), cipherSuite), socketFactoryWithCipherSuite(clientCertificates.sslSocketFactory(), cipherSuite),
clientCertificates.trustManager()) clientCertificates.trustManager())
.connectionSpecs(Arrays.asList(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .connectionSpecs(asList(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.cipherSuites(cipherSuite) .cipherSuites(cipherSuite)
.build())) .build()))
.build(); .build();
@ -1264,7 +1262,7 @@ public final class CallTest {
@Test public void cleartextCallsFailWhenCleartextIsDisabled() throws Exception { @Test public void cleartextCallsFailWhenCleartextIsDisabled() throws Exception {
// Configure the client with only TLS configurations. No cleartext! // Configure the client with only TLS configurations. No cleartext!
client = client.newBuilder() client = client.newBuilder()
.connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)) .connectionSpecs(asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
.build(); .build();
server.enqueue(new MockResponse()); server.enqueue(new MockResponse());
@ -1359,7 +1357,7 @@ public final class CallTest {
client.newCall(request).execute(); client.newCall(request).execute();
fail(); fail();
} catch (SSLPeerUnverifiedException expected) { } 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("/"); executeSynchronously("/");
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getHeader("User-Agent") assertThat(recordedRequest.getHeader("User-Agent")).matches(Version.userAgent());
.matches(Version.userAgent())).isTrue();
} }
@Test public void setFollowRedirectsFalse() throws Exception { @Test public void setFollowRedirectsFalse() throws Exception {
@ -2885,7 +2882,7 @@ public final class CallTest {
assertThat(get.getHeader("Private")).isEqualTo("Secret"); assertThat(get.getHeader("Private")).isEqualTo("Secret");
assertThat(get.getHeader("User-Agent")).isEqualTo("App 1.0"); 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. */ /** Respond to a proxy authorization challenge. */
@ -3147,7 +3144,7 @@ public final class CallTest {
assertThat(connect2.getMethod()).isEqualTo("CONNECT"); assertThat(connect2.getMethod()).isEqualTo("CONNECT");
assertThat(connect2.getHeader("Proxy-Authorization")).isEqualTo(credential); 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 { @Test public void interceptorGetsHttp2() throws Exception {
@ -3284,28 +3281,28 @@ public final class CallTest {
upload(true, 1048576, 256); upload(true, 1048576, 256);
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576);
assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); assertThat(recordedRequest.getChunkSizes()).isNotEmpty();
} }
@Test public void uploadBodyLargeChunkedEncoding() throws Exception { @Test public void uploadBodyLargeChunkedEncoding() throws Exception {
upload(true, 1048576, 65536); upload(true, 1048576, 65536);
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576);
assertThat(recordedRequest.getChunkSizes().isEmpty()).isFalse(); assertThat(recordedRequest.getChunkSizes()).isNotEmpty();
} }
@Test public void uploadBodySmallFixedLength() throws Exception { @Test public void uploadBodySmallFixedLength() throws Exception {
upload(false, 1048576, 256); upload(false, 1048576, 256);
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576);
assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); assertThat(recordedRequest.getChunkSizes()).isEmpty();
} }
@Test public void uploadBodyLargeFixedLength() throws Exception { @Test public void uploadBodyLargeFixedLength() throws Exception {
upload(false, 1048576, 65536); upload(false, 1048576, 65536);
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getBodySize()).isEqualTo(1048576); assertThat(recordedRequest.getBodySize()).isEqualTo(1048576);
assertThat(recordedRequest.getChunkSizes().isEmpty()).isTrue(); assertThat(recordedRequest.getChunkSizes()).isEmpty();
} }
private void upload( private void upload(
@ -3400,10 +3397,10 @@ public final class CallTest {
awaitGarbageCollection(); awaitGarbageCollection();
String message = logHandler.take(); String message = logHandler.take();
assertThat(message.contains("A connection to " + server.url("/") + " was leaked." assertThat(message).contains("A connection to " + server.url("/") + " was leaked."
+ " Did you forget to close a response body?")).isTrue(); + " Did you forget to close a response body?");
assertThat(message.contains("okhttp3.RealCall.execute(")).isTrue(); assertThat(message).contains("okhttp3.RealCall.execute(");
assertThat(message.contains("okhttp3.CallTest.leakedResponseBodyLogsStackTrace(")).isTrue(); assertThat(message).contains("okhttp3.CallTest.leakedResponseBodyLogsStackTrace(");
} finally { } finally {
logger.setLevel(original); logger.setLevel(original);
} }
@ -3443,10 +3440,10 @@ public final class CallTest {
awaitGarbageCollection(); awaitGarbageCollection();
String message = logHandler.take(); String message = logHandler.take();
assertThat(message.contains("A connection to " + server.url("/") + " was leaked." assertThat(message).contains("A connection to " + server.url("/") + " was leaked."
+ " Did you forget to close a response body?")).isTrue(); + " Did you forget to close a response body?");
assertThat(message.contains("okhttp3.RealCall.enqueue(")).isTrue(); assertThat(message).contains("okhttp3.RealCall.enqueue(");
assertThat(message.contains("okhttp3.CallTest.asyncLeakedResponseBodyLogsStackTrace(")).isTrue(); assertThat(message).contains("okhttp3.CallTest.asyncLeakedResponseBodyLogsStackTrace(");
} finally { } finally {
logger.setLevel(original); logger.setLevel(original);
} }
@ -3719,7 +3716,7 @@ public final class CallTest {
private void enableProtocol(Protocol protocol) { private void enableProtocol(Protocol protocol) {
enableTls(); enableTls();
client = client.newBuilder() client = client.newBuilder()
.protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) .protocols(asList(protocol, Protocol.HTTP_1_1))
.build(); .build();
server.setProtocols(client.protocols()); server.setProtocols(client.protocols());
} }

View File

@ -23,6 +23,7 @@ import okhttp3.CertificatePinner.Pin;
import okhttp3.tls.HeldCertificate; import okhttp3.tls.HeldCertificate;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -219,7 +220,7 @@ public final class CertificatePinnerTest {
.add("second.com", certC1Sha256Pin) .add("second.com", certC1Sha256Pin)
.build(); .build();
List<Pin> expectedPins = Arrays.asList( List<Pin> expectedPins = asList(
new Pin("first.com", certA1Sha256Pin), new Pin("first.com", certA1Sha256Pin),
new Pin("first.com", certB1Sha256Pin)); new Pin("first.com", certB1Sha256Pin));
assertThat(certificatePinner.findMatchingPins("first.com")).isEqualTo(expectedPins); assertThat(certificatePinner.findMatchingPins("first.com")).isEqualTo(expectedPins);
@ -232,7 +233,7 @@ public final class CertificatePinnerTest {
.add("b.example.com", certC1Sha256Pin) .add("b.example.com", certC1Sha256Pin)
.build(); .build();
List<Pin> expectedPins = Arrays.asList( List<Pin> expectedPins = asList(
new Pin("*.example.com", certA1Sha256Pin), new Pin("*.example.com", certA1Sha256Pin),
new Pin("a.example.com", certB1Sha256Pin)); new Pin("a.example.com", certB1Sha256Pin));
assertThat(certificatePinner.findMatchingPins("a.example.com")).isEqualTo(expectedPins); assertThat(certificatePinner.findMatchingPins("a.example.com")).isEqualTo(expectedPins);
@ -253,10 +254,10 @@ public final class CertificatePinnerTest {
.add("*.MyExample.Com", certB1Sha256Pin) .add("*.MyExample.Com", certB1Sha256Pin)
.build(); .build();
List<Pin> expectedPin1 = Arrays.asList(new Pin("EXAMPLE.com", certA1Sha256Pin)); List<Pin> expectedPin1 = asList(new Pin("EXAMPLE.com", certA1Sha256Pin));
assertThat(certificatePinner.findMatchingPins("example.com")).isEqualTo(expectedPin1); assertThat(certificatePinner.findMatchingPins("example.com")).isEqualTo(expectedPin1);
List<Pin> expectedPin2 = Arrays.asList(new Pin("*.MyExample.Com", certB1Sha256Pin)); List<Pin> expectedPin2 = asList(new Pin("*.MyExample.Com", certB1Sha256Pin));
assertThat(certificatePinner.findMatchingPins("a.myexample.com")).isEqualTo(expectedPin2); assertThat(certificatePinner.findMatchingPins("a.myexample.com")).isEqualTo(expectedPin2);
} }
@ -265,7 +266,7 @@ public final class CertificatePinnerTest {
.add("σkhttp.com", certA1Sha256Pin) .add("σkhttp.com", certA1Sha256Pin)
.build(); .build();
List<Pin> expectedPin = Arrays.asList(new Pin("σkhttp.com", certA1Sha256Pin)); List<Pin> expectedPin = asList(new Pin("σkhttp.com", certA1Sha256Pin));
assertThat(certificatePinner.findMatchingPins("xn--khttp-fde.com")).isEqualTo(expectedPin); assertThat(certificatePinner.findMatchingPins("xn--khttp-fde.com")).isEqualTo(expectedPin);
} }

View File

@ -34,6 +34,7 @@ import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -259,7 +260,7 @@ public final class ConnectionCoalescingTest {
HttpUrl sanUrl = url.newBuilder().host("san.com").build(); HttpUrl sanUrl = url.newBuilder().host("san.com").build();
dns.set("san.com", 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))); serverIps.get(0)));
assert200Http2Response(execute(sanUrl), "san.com"); assert200Http2Response(execute(sanUrl), "san.com");

View File

@ -30,6 +30,7 @@ import org.junit.Test;
import org.junit.rules.TestRule; import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import static java.util.Arrays.asList;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -355,7 +356,7 @@ public final class ConnectionReuseTest {
.sslSocketFactory( .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()) handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
.protocols(Arrays.asList(protocols)) .protocols(asList(protocols))
.build(); .build();
server.useHttps(handshakeCertificates.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
server.setProtocols(client.protocols()); server.setProtocols(client.protocols());

View File

@ -15,14 +15,15 @@
*/ */
package okhttp3; package okhttp3;
import java.util.Arrays; import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -94,13 +95,11 @@ public final class ConnectionSpecTest {
assertThat(tlsSpec.isCompatible(socket)).isTrue(); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, false /* isFallback */); 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<String> expectedCipherSet = assertThat(socket.getEnabledCipherSuites()).containsExactlyInAnyOrder(
set( CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
assertThat(expectedCipherSet).isEqualTo(expectedCipherSet);
} }
@Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception { @Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
@ -122,16 +121,15 @@ public final class ConnectionSpecTest {
assertThat(tlsSpec.isCompatible(socket)).isTrue(); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, true /* isFallback */); 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<String> expectedCipherSet = List<String> expectedCipherSuites = new ArrayList<>();
set( expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName, expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName); if (asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { expectedCipherSuites.add("TLS_FALLBACK_SCSV");
expectedCipherSet.add("TLS_FALLBACK_SCSV");
} }
assertThat(expectedCipherSet).isEqualTo(expectedCipherSet); assertThat(socket.getEnabledCipherSuites()).containsExactlyElementsOf(expectedCipherSuites);
} }
@Test public void tls_explicitCiphers() throws Exception { @Test public void tls_explicitCiphers() throws Exception {
@ -154,13 +152,14 @@ public final class ConnectionSpecTest {
assertThat(tlsSpec.isCompatible(socket)).isTrue(); assertThat(tlsSpec.isCompatible(socket)).isTrue();
tlsSpec.apply(socket, true /* isFallback */); 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<String> expectedCipherSet = set(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); List<String> expectedCipherSuites = new ArrayList<>();
if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) { expectedCipherSuites.add(CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
expectedCipherSet.add("TLS_FALLBACK_SCSV"); 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 { @Test public void tls_stringCiphersAndVersions() throws Exception {
@ -210,7 +209,7 @@ public final class ConnectionSpecTest {
}); });
tlsSpec.apply(sslSocket, false); 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_SHA.javaName,
CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName); CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName);
} }
@ -228,7 +227,7 @@ public final class ConnectionSpecTest {
}); });
tlsSpec.apply(sslSocket, false); tlsSpec.apply(sslSocket, false);
assertThat(Arrays.asList(sslSocket.getEnabledProtocols())).containsExactly( assertThat(sslSocket.getEnabledProtocols()).containsExactly(
TlsVersion.SSL_3_0.javaName(), TlsVersion.TLS_1_1.javaName()); 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(ConnectionSpec.CLEARTEXT)).isTrue();
assertThat(set.remove(allTlsVersions)).isTrue(); assertThat(set.remove(allTlsVersions)).isTrue();
assertThat(set.remove(allCipherSuites)).isTrue(); assertThat(set.remove(allCipherSuites)).isTrue();
assertThat(set.isEmpty()).isTrue(); assertThat(set).isEmpty();
} }
@Test public void allEnabledToString() throws Exception { @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], " ("ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], "
+ "supportsTlsExtensions=true)")); + "supportsTlsExtensions=true)"));
} }
@SafeVarargs
private static <T> Set<T> set(T... values) {
return new LinkedHashSet<>(Arrays.asList(values));
}
} }

View File

@ -27,6 +27,7 @@ import org.junit.After;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class ConscryptTest { public class ConscryptTest {
@ -53,7 +54,7 @@ public class ConscryptTest {
.supportsTlsExtensions(true) .supportsTlsExtensions(true)
.build(); .build();
return new OkHttpClient.Builder().connectionSpecs(Arrays.asList(spec)).build(); return new OkHttpClient.Builder().connectionSpecs(asList(spec)).build();
} }
private static void assumeConscrypt() { private static void assumeConscrypt() {

View File

@ -25,6 +25,7 @@ import okhttp3.internal.Util;
import okhttp3.internal.http.HttpDate; import okhttp3.internal.http.HttpDate;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -553,7 +554,7 @@ public final class CookieTest {
} }
@Test public void equalsAndHashCode() throws Exception { @Test public void equalsAndHashCode() throws Exception {
List<String> cookieStrings = Arrays.asList( List<String> cookieStrings = asList(
"a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly", "a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly",
"a= ; 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", "a=b; Domain=example.com; Max-Age=5; Secure; HttpOnly",

View File

@ -23,7 +23,6 @@ import java.net.HttpCookie;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.URI; import java.net.URI;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@ -35,6 +34,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER; import static java.net.CookiePolicy.ACCEPT_ORIGINAL_SERVER;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset; import static org.assertj.core.data.Offset.offset;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -70,7 +70,7 @@ public class CookiesTest {
assertThat(cookie.getComment()).isNull(); assertThat(cookie.getComment()).isNull();
assertThat(cookie.getCommentURL()).isNull(); assertThat(cookie.getCommentURL()).isNull();
assertThat(cookie.getDiscard()).isFalse(); assertThat(cookie.getDiscard()).isFalse();
assertThat(cookie.getMaxAge() > 100000000000L).isTrue(); assertThat(cookie.getMaxAge()).isGreaterThan(100000000000L);
assertThat(cookie.getPath()).isEqualTo("/path"); assertThat(cookie.getPath()).isEqualTo("/path");
assertThat(cookie.getSecure()).isTrue(); assertThat(cookie.getSecure()).isTrue();
assertThat(cookie.getVersion()).isEqualTo(0); assertThat(cookie.getVersion()).isEqualTo(0);
@ -280,7 +280,7 @@ public class CookiesTest {
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
HttpUrl url = HttpUrl.get("https://www.squareup.com/"); 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"))); Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertThat(actualCookies.size()).isEqualTo(1); assertThat(actualCookies.size()).isEqualTo(1);
@ -293,7 +293,7 @@ public class CookiesTest {
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
HttpUrl url = HttpUrl.get("https://www.squareup.com/"); 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"))); Cookie.parse(url, "a=android; Domain=.squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertThat(actualCookies.size()).isEqualTo(1); assertThat(actualCookies.size()).isEqualTo(1);
@ -306,7 +306,7 @@ public class CookiesTest {
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
HttpUrl url = HttpUrl.get("https://squareup.com/"); HttpUrl url = HttpUrl.get("https://squareup.com/");
cookieJar.saveFromResponse(url, Arrays.asList( cookieJar.saveFromResponse(url, asList(
Cookie.parse(url, "a=android; Domain=squareup.com"))); Cookie.parse(url, "a=android; Domain=squareup.com")));
List<Cookie> actualCookies = cookieJar.loadForRequest(url); List<Cookie> actualCookies = cookieJar.loadForRequest(url);
assertThat(actualCookies.size()).isEqualTo(1); assertThat(actualCookies.size()).isEqualTo(1);
@ -319,7 +319,7 @@ public class CookiesTest {
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager); JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);
HttpUrl url1 = HttpUrl.get("https://api.squareup.com/"); 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"))); Cookie.parse(url1, "a=android; Domain=api.squareup.com")));
HttpUrl url2 = HttpUrl.get("https://www.squareup.com/"); HttpUrl url2 = HttpUrl.get("https://www.squareup.com/");

View File

@ -3,11 +3,8 @@ package okhttp3;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionException;
@ -175,8 +172,8 @@ public final class DispatcherTest {
a5.enqueue(callback); a5.enqueue(callback);
assertThat(dispatcher.runningCallsCount()).isEqualTo(3); assertThat(dispatcher.runningCallsCount()).isEqualTo(3);
assertThat(dispatcher.queuedCallsCount()).isEqualTo(2); assertThat(dispatcher.queuedCallsCount()).isEqualTo(2);
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2, a3)); assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2, a3);
assertThat(set(dispatcher.queuedCalls())).isEqualTo(set(a4, a5)); assertThat(dispatcher.queuedCalls()).containsExactlyInAnyOrder(a4, a5);
} }
@Test public void synchronousCallAccessors() throws Exception { @Test public void synchronousCallAccessors() throws Exception {
@ -205,13 +202,13 @@ public final class DispatcherTest {
ready.await(); ready.await();
assertThat(dispatcher.runningCallsCount()).isEqualTo(2); assertThat(dispatcher.runningCallsCount()).isEqualTo(2);
assertThat(dispatcher.queuedCallsCount()).isEqualTo(0); assertThat(dispatcher.queuedCallsCount()).isEqualTo(0);
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2)); assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2);
assertThat(dispatcher.queuedCalls()).isEmpty(); assertThat(dispatcher.queuedCalls()).isEmpty();
// Cancel some calls. That doesn't impact running or queued. // Cancel some calls. That doesn't impact running or queued.
a2.cancel(); a2.cancel();
a3.cancel(); a3.cancel();
assertThat(set(dispatcher.runningCalls())).isEqualTo(set(a1, a2)); assertThat(dispatcher.runningCalls()).containsExactlyInAnyOrder(a1, a2);
assertThat(dispatcher.queuedCalls()).isEmpty(); assertThat(dispatcher.queuedCalls()).isEmpty();
// Let the calls finish. // Let the calls finish.
@ -319,15 +316,6 @@ public final class DispatcherTest {
"CallFailed"); "CallFailed");
} }
@SafeVarargs
private final <T> Set<T> set(T... values) {
return set(Arrays.asList(values));
}
private <T> Set<T> set(List<T> list) {
return new LinkedHashSet<>(list);
}
private Thread makeSynchronousCall(Call call) { private Thread makeSynchronousCall(Call call) {
Thread thread = new Thread(() -> { Thread thread = new Thread(() -> {
try { try {

View File

@ -18,8 +18,6 @@ package okhttp3;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import okhttp3.internal.RecordingOkAuthenticator; import okhttp3.internal.RecordingOkAuthenticator;
import okhttp3.internal.duplex.AsyncRequestBody; import okhttp3.internal.duplex.AsyncRequestBody;
@ -36,6 +34,7 @@ import org.junit.Test;
import org.junit.rules.TestRule; import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import static java.util.Arrays.asList;
import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.assertTrue;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -234,12 +233,12 @@ public final class DuplexTest {
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired",
"RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestBodyEnd", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestBodyEnd",
"ConnectionReleased", "CallEnd"); "ConnectionReleased", "CallEnd");
assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void duplexWith100Continue() throws Exception { @Test public void duplexWith100Continue() throws Exception {
@ -316,13 +315,13 @@ public final class DuplexTest {
mockDuplexResponseBody.awaitSuccess(); mockDuplexResponseBody.awaitSuccess();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired",
"RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart", "RequestHeadersStart", "RequestHeadersEnd", "RequestBodyStart", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd", "RequestFailed");
assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
/** /**
@ -494,7 +493,7 @@ public final class DuplexTest {
private void enableProtocol(Protocol protocol) { private void enableProtocol(Protocol protocol) {
enableTls(); enableTls();
client = client.newBuilder() client = client.newBuilder()
.protocols(Arrays.asList(protocol, Protocol.HTTP_1_1)) .protocols(asList(protocol, Protocol.HTTP_1_1))
.build(); .build();
server.setProtocols(client.protocols()); server.setProtocols(client.protocols());
} }

View File

@ -21,7 +21,6 @@ import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Proxy; import java.net.Proxy;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -52,22 +51,21 @@ import okhttp3.mockwebserver.SocketPolicy;
import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HandshakeCertificates;
import okio.Buffer; import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import org.assertj.core.api.Assertions;
import org.hamcrest.BaseMatcher; import org.hamcrest.BaseMatcher;
import org.hamcrest.CoreMatchers; import org.hamcrest.CoreMatchers;
import org.hamcrest.Description; import org.hamcrest.Description;
import org.hamcrest.Matcher; import org.hamcrest.Matcher;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.any;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat; import static org.junit.Assume.assumeThat;
@ -105,15 +103,14 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.body().string()).isEqualTo("abc"); assertThat(response.body().string()).isEqualTo("abc");
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void successfulCallEventSequenceForEnqueue() throws Exception { @Test public void successfulCallEventSequenceForEnqueue() throws Exception {
@ -140,11 +137,10 @@ public final class EventListenerTest {
completionLatch.await(); completionLatch.await();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void failedCallEventSequence() { @Test public void failedCallEventSequence() {
@ -159,14 +155,13 @@ public final class EventListenerTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertThat(expected.getMessage(), either(equalTo("timeout")).or(equalTo("Read timed out"))); assertThat(expected.getMessage()).isIn("timeout", "Read timed out");
} }
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseFailed", "ConnectionReleased",
"CallFailed"); "CallFailed");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void failedDribbledCallEventSequence() throws IOException { @Test public void failedDribbledCallEventSequence() throws IOException {
@ -188,17 +183,15 @@ public final class EventListenerTest {
response.body.string(); response.body.string();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
assertThat(expected.getMessage(), equalTo("unexpected end of stream")); assertThat(expected.getMessage()).isEqualTo("unexpected end of stream");
} }
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseFailed", "ConnectionReleased", "CallFailed"); "ResponseFailed", "ConnectionReleased", "CallFailed");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
ResponseFailed responseFailed = listener.removeUpToEvent(ResponseFailed.class); ResponseFailed responseFailed = listener.removeUpToEvent(ResponseFailed.class);
Assertions.assertThat(responseFailed.ioe.getMessage()).isEqualTo( assertThat(responseFailed.ioe.getMessage()).isEqualTo("unexpected end of stream");
"unexpected end of stream");
} }
@Test public void canceledCallEventSequence() { @Test public void canceledCallEventSequence() {
@ -210,11 +203,10 @@ public final class EventListenerTest {
call.execute(); call.execute();
fail(); fail();
} catch (IOException expected) { } catch (IOException expected) {
Assertions.assertThat(expected.getMessage()).isEqualTo("Canceled"); assertThat(expected.getMessage()).isEqualTo("Canceled");
} }
List<String> expectedEvents = Arrays.asList("CallStart", "CallFailed"); assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallFailed");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void assertSuccessfulEventOrder(Matcher<Response> responseMatcher) throws IOException { private void assertSuccessfulEventOrder(Matcher<Response> responseMatcher) throws IOException {
@ -222,23 +214,22 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().string(); response.body().string();
response.body().close(); response.body().close();
assumeThat(response, responseMatcher); assumeThat(response, responseMatcher);
List<String> expectedEvents = asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired", "SecureConnectStart", "SecureConnectEnd", "ConnectEnd", "ConnectionAcquired",
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void secondCallEventSequence() throws IOException { @Test public void secondCallEventSequence() throws IOException {
enableTlsWithTunnel(false); 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());
server.enqueue(new MockResponse()); server.enqueue(new MockResponse());
@ -254,11 +245,9 @@ public final class EventListenerTest {
Response response = call.execute(); Response response = call.execute();
response.close(); response.close();
List<String> expectedEvents = asList("CallStart", "ConnectionAcquired", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "ConnectionAcquired",
"RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void assertBytesReadWritten(RecordingEventListener listener, private void assertBytesReadWritten(RecordingEventListener listener,
@ -267,34 +256,30 @@ public final class EventListenerTest {
if (requestHeaderLength != null) { if (requestHeaderLength != null) {
RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class); RequestHeadersEnd responseHeadersEnd = listener.removeUpToEvent(RequestHeadersEnd.class);
assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength); Assert.assertThat("request header length", responseHeadersEnd.headerLength, requestHeaderLength);
} else { } else {
Assertions.assertThat(listener.recordedEventTypes().contains("RequestHeadersEnd")).overridingErrorMessage( assertThat(listener.recordedEventTypes()).doesNotContain("RequestHeadersEnd");
"Found RequestHeadersEnd").isFalse();
} }
if (requestBodyBytes != null) { if (requestBodyBytes != null) {
RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class); RequestBodyEnd responseBodyEnd = listener.removeUpToEvent(RequestBodyEnd.class);
assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes); Assert.assertThat("request body bytes", responseBodyEnd.bytesWritten, requestBodyBytes);
} else { } else {
Assertions.assertThat(listener.recordedEventTypes().contains("RequestBodyEnd")).overridingErrorMessage( assertThat(listener.recordedEventTypes()).doesNotContain("RequestBodyEnd");
"Found RequestBodyEnd").isFalse();
} }
if (responseHeaderLength != null) { if (responseHeaderLength != null) {
ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class); ResponseHeadersEnd responseHeadersEnd = listener.removeUpToEvent(ResponseHeadersEnd.class);
assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength); Assert.assertThat("response header length", responseHeadersEnd.headerLength, responseHeaderLength);
} else { } else {
Assertions.assertThat(listener.recordedEventTypes().contains("ResponseHeadersEnd")).overridingErrorMessage( assertThat(listener.recordedEventTypes()).doesNotContain("ResponseHeadersEnd");
"Found ResponseHeadersEnd").isFalse();
} }
if (responseBodyBytes != null) { if (responseBodyBytes != null) {
ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class); ResponseBodyEnd responseBodyEnd = listener.removeUpToEvent(ResponseBodyEnd.class);
assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes); Assert.assertThat("response body bytes", responseBodyEnd.bytesRead, responseBodyBytes);
} else { } else {
Assertions.assertThat(listener.recordedEventTypes().contains("ResponseBodyEnd")).overridingErrorMessage( assertThat(listener.recordedEventTypes()).doesNotContain("ResponseBodyEnd");
"Found ResponseBodyEnd").isFalse();
} }
} }
@ -336,7 +321,7 @@ public final class EventListenerTest {
@Test public void successfulEmptyH2CallEventSequence() throws IOException { @Test public void successfulEmptyH2CallEventSequence() throws IOException {
enableTlsWithTunnel(false); 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());
assertSuccessfulEventOrder(matchesProtocol(Protocol.HTTP_2)); assertSuccessfulEventOrder(matchesProtocol(Protocol.HTTP_2));
@ -347,7 +332,7 @@ public final class EventListenerTest {
@Test public void successfulEmptyHttpsCallEventSequence() throws IOException { @Test public void successfulEmptyHttpsCallEventSequence() throws IOException {
enableTlsWithTunnel(false); enableTlsWithTunnel(false);
server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); server.setProtocols(asList(Protocol.HTTP_1_1));
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody("abc")); .setBody("abc"));
@ -359,7 +344,7 @@ public final class EventListenerTest {
@Test public void successfulChunkedHttpsCallEventSequence() throws IOException { @Test public void successfulChunkedHttpsCallEventSequence() throws IOException {
enableTlsWithTunnel(false); enableTlsWithTunnel(false);
server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); server.setProtocols(asList(Protocol.HTTP_1_1));
server.enqueue( server.enqueue(
new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2)); new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2));
@ -371,7 +356,7 @@ public final class EventListenerTest {
@Test public void successfulChunkedH2CallEventSequence() throws IOException { @Test public void successfulChunkedH2CallEventSequence() throws IOException {
enableTlsWithTunnel(false); 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( server.enqueue(
new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2)); new MockResponse().setBodyDelay(100, TimeUnit.MILLISECONDS).setChunkedBody("Hello!", 2));
@ -388,17 +373,17 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class); DnsStart dnsStart = listener.removeUpToEvent(DnsStart.class);
Assertions.assertThat(dnsStart.call).isSameAs(call); assertThat(dnsStart.call).isSameAs(call);
Assertions.assertThat(dnsStart.domainName).isEqualTo(server.getHostName()); assertThat(dnsStart.domainName).isEqualTo(server.getHostName());
DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class); DnsEnd dnsEnd = listener.removeUpToEvent(DnsEnd.class);
Assertions.assertThat(dnsEnd.call).isSameAs(call); assertThat(dnsEnd.call).isSameAs(call);
Assertions.assertThat(dnsEnd.domainName).isEqualTo(server.getHostName()); assertThat(dnsEnd.domainName).isEqualTo(server.getHostName());
Assertions.assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1); assertThat(dnsEnd.inetAddressList.size()).isEqualTo(1);
} }
@Test public void noDnsLookupOnPooledConnection() throws IOException { @Test public void noDnsLookupOnPooledConnection() throws IOException {
@ -410,7 +395,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.code()).isEqualTo(200); assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
listener.clearAllEvents(); listener.clearAllEvents();
@ -419,12 +404,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.code()).isEqualTo(200); assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes(); List<String> recordedEvents = listener.recordedEventTypes();
Assertions.assertThat(recordedEvents.contains("DnsStart")).isFalse(); assertThat(recordedEvents).doesNotContain("DnsStart");
Assertions.assertThat(recordedEvents.contains("DnsEnd")).isFalse(); assertThat(recordedEvents).doesNotContain("DnsEnd");
} }
@Test public void multipleDnsLookupsForSingleCall() throws IOException { @Test public void multipleDnsLookupsForSingleCall() throws IOException {
@ -445,7 +430,7 @@ public final class EventListenerTest {
.url("http://fakeurl:" + server.getPort()) .url("http://fakeurl:" + server.getPort())
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
@ -470,9 +455,8 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
Assertions.assertThat(callFailed.call).isSameAs(call); assertThat(callFailed.call).isSameAs(call);
boolean condition = callFailed.ioe instanceof UnknownHostException; assertThat(callFailed.ioe).isInstanceOf(UnknownHostException.class);
Assertions.assertThat(condition).isTrue();
} }
@Test public void emptyDnsLookup() { @Test public void emptyDnsLookup() {
@ -493,9 +477,8 @@ public final class EventListenerTest {
listener.removeUpToEvent(DnsStart.class); listener.removeUpToEvent(DnsStart.class);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
Assertions.assertThat(callFailed.call).isSameAs(call); assertThat(callFailed.call).isSameAs(call);
boolean condition = callFailed.ioe instanceof UnknownHostException; assertThat(callFailed.ioe).isInstanceOf(UnknownHostException.class);
Assertions.assertThat(condition).isTrue();
} }
@Test public void successfulConnect() throws IOException { @Test public void successfulConnect() throws IOException {
@ -505,21 +488,21 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0); InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
Assertions.assertThat(connectStart.call).isSameAs(call); assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
Assertions.assertThat(connectEnd.call).isSameAs(call); assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void failedConnect() throws UnknownHostException { @Test public void failedConnect() throws UnknownHostException {
@ -540,15 +523,15 @@ public final class EventListenerTest {
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
Assertions.assertThat(connectStart.call).isSameAs(call); assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY); assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY);
ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class); ConnectFailed connectFailed = listener.removeUpToEvent(ConnectFailed.class);
Assertions.assertThat(connectFailed.call).isSameAs(call); assertThat(connectFailed.call).isSameAs(call);
Assertions.assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectFailed.protocol).isNull(); assertThat(connectFailed.protocol).isNull();
Assertions.assertThat(connectFailed.ioe).isNotNull(); assertThat(connectFailed.ioe).isNotNull();
} }
@Test public void multipleConnectsForSingleCall() throws IOException { @Test public void multipleConnectsForSingleCall() throws IOException {
@ -565,7 +548,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
@ -585,21 +568,21 @@ public final class EventListenerTest {
.url("http://www.fakeurl") .url("http://www.fakeurl")
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetAddress address = client.dns().lookup(server.getHostName()).get(0); InetAddress address = client.dns().lookup(server.getHostName()).get(0);
InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort()); InetSocketAddress expectedAddress = new InetSocketAddress(address, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
Assertions.assertThat(connectStart.call).isSameAs(call); assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress()); assertThat(connectStart.proxy).isEqualTo(server.toProxyAddress());
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
Assertions.assertThat(connectEnd.call).isSameAs(call); assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void successfulSocksProxyConnect() throws Exception { @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()) .url("http://" + SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS + ":" + server.getPort())
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved( InetSocketAddress expectedAddress = InetSocketAddress.createUnresolved(
SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, server.getPort()); SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, server.getPort());
ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class); ConnectStart connectStart = listener.removeUpToEvent(ConnectStart.class);
Assertions.assertThat(connectStart.call).isSameAs(call); assertThat(connectStart.call).isSameAs(call);
Assertions.assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectStart.proxy).isEqualTo(proxy); assertThat(connectStart.proxy).isEqualTo(proxy);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
Assertions.assertThat(connectEnd.call).isSameAs(call); assertThat(connectEnd.call).isSameAs(call);
Assertions.assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress); assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress);
Assertions.assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1); assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1);
} }
@Test public void authenticatingTunnelProxyConnect() throws IOException { @Test public void authenticatingTunnelProxyConnect() throws IOException {
@ -653,13 +636,13 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class); ConnectEnd connectEnd = listener.removeUpToEvent(ConnectEnd.class);
Assertions.assertThat(connectEnd.protocol).isNull(); assertThat(connectEnd.protocol).isNull();
listener.removeUpToEvent(ConnectStart.class); listener.removeUpToEvent(ConnectStart.class);
listener.removeUpToEvent(ConnectEnd.class); listener.removeUpToEvent(ConnectEnd.class);
@ -673,15 +656,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
Assertions.assertThat(secureStart.call).isSameAs(call); assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
Assertions.assertThat(secureEnd.call).isSameAs(call); assertThat(secureEnd.call).isSameAs(call);
Assertions.assertThat(secureEnd.handshake).isNotNull(); assertThat(secureEnd.handshake).isNotNull();
} }
@Test public void failedSecureConnect() { @Test public void failedSecureConnect() {
@ -699,11 +682,11 @@ public final class EventListenerTest {
} }
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
Assertions.assertThat(secureStart.call).isSameAs(call); assertThat(secureStart.call).isSameAs(call);
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
Assertions.assertThat(callFailed.call).isSameAs(call); assertThat(callFailed.call).isSameAs(call);
Assertions.assertThat(callFailed.ioe).isNotNull(); assertThat(callFailed.ioe).isNotNull();
} }
@Test public void secureConnectWithTunnel() throws IOException { @Test public void secureConnectWithTunnel() throws IOException {
@ -720,15 +703,15 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class); SecureConnectStart secureStart = listener.removeUpToEvent(SecureConnectStart.class);
Assertions.assertThat(secureStart.call).isSameAs(call); assertThat(secureStart.call).isSameAs(call);
SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class); SecureConnectEnd secureEnd = listener.removeUpToEvent(SecureConnectEnd.class);
Assertions.assertThat(secureEnd.call).isSameAs(call); assertThat(secureEnd.call).isSameAs(call);
Assertions.assertThat(secureEnd.handshake).isNotNull(); assertThat(secureEnd.handshake).isNotNull();
} }
@Test public void multipleSecureConnectsForSingleCall() throws IOException { @Test public void multipleSecureConnectsForSingleCall() throws IOException {
@ -745,7 +728,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
listener.removeUpToEvent(SecureConnectStart.class); listener.removeUpToEvent(SecureConnectStart.class);
@ -769,7 +752,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.code()).isEqualTo(200); assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
listener.clearAllEvents(); listener.clearAllEvents();
@ -778,12 +761,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.code()).isEqualTo(200); assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
List<String> recordedEvents = listener.recordedEventTypes(); List<String> recordedEvents = listener.recordedEventTypes();
Assertions.assertThat(recordedEvents.contains("SecureConnectStart")).isFalse(); assertThat(recordedEvents).doesNotContain("SecureConnectStart");
Assertions.assertThat(recordedEvents.contains("SecureConnectEnd")).isFalse(); assertThat(recordedEvents).doesNotContain("SecureConnectEnd");
} }
@Test public void successfulConnectionFound() throws IOException { @Test public void successfulConnectionFound() throws IOException {
@ -793,12 +776,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
response.body().close(); response.body().close();
ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired = listener.removeUpToEvent(ConnectionAcquired.class);
Assertions.assertThat(connectionAcquired.call).isSameAs(call); assertThat(connectionAcquired.call).isSameAs(call);
Assertions.assertThat(connectionAcquired.connection).isNotNull(); assertThat(connectionAcquired.connection).isNotNull();
} }
@Test public void noConnectionFoundOnFollowUp() throws IOException { @Test public void noConnectionFoundOnFollowUp() throws IOException {
@ -812,12 +795,12 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); 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);
List<String> remainingEvents = listener.recordedEventTypes(); List<String> remainingEvents = listener.recordedEventTypes();
Assertions.assertThat(remainingEvents.contains("ConnectionAcquired")).isFalse(); assertThat(remainingEvents).doesNotContain("ConnectionAcquired");
} }
@Test public void pooledConnectionFound() throws IOException { @Test public void pooledConnectionFound() throws IOException {
@ -829,7 +812,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.code()).isEqualTo(200); assertThat(response1.code()).isEqualTo(200);
response1.body().close(); response1.body().close();
ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired1 = listener.removeUpToEvent(ConnectionAcquired.class);
@ -839,11 +822,11 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.code()).isEqualTo(200); assertThat(response2.code()).isEqualTo(200);
response2.body().close(); response2.body().close();
ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class); ConnectionAcquired connectionAcquired2 = listener.removeUpToEvent(ConnectionAcquired.class);
Assertions.assertThat(connectionAcquired2.connection).isSameAs( assertThat(connectionAcquired2.connection).isSameAs(
connectionAcquired1.connection); connectionAcquired1.connection);
} }
@ -859,7 +842,7 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); 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);
listener.removeUpToEvent(ConnectionAcquired.class); listener.removeUpToEvent(ConnectionAcquired.class);
@ -867,13 +850,13 @@ public final class EventListenerTest {
@Test public void responseBodyFailHttp1OverHttps() throws IOException { @Test public void responseBodyFailHttp1OverHttps() throws IOException {
enableTlsWithTunnel(false); enableTlsWithTunnel(false);
server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); server.setProtocols(asList(Protocol.HTTP_1_1));
responseBodyFail(Protocol.HTTP_1_1); responseBodyFail(Protocol.HTTP_1_1);
} }
@Test public void responseBodyFailHttp2OverHttps() throws IOException { @Test public void responseBodyFailHttp2OverHttps() throws IOException {
enableTlsWithTunnel(false); 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); responseBodyFail(Protocol.HTTP_2);
} }
@ -896,7 +879,7 @@ public final class EventListenerTest {
// soft failure since client may not support depending on Platform // soft failure since client may not support depending on Platform
assumeThat(response, matchesProtocol(Protocol.HTTP_2)); assumeThat(response, matchesProtocol(Protocol.HTTP_2));
} }
Assertions.assertThat(response.protocol()).isEqualTo(expectedProtocol); assertThat(response.protocol()).isEqualTo(expectedProtocol);
try { try {
response.body.string(); response.body.string();
fail(); fail();
@ -904,7 +887,7 @@ public final class EventListenerTest {
} }
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
Assertions.assertThat(callFailed.ioe).isNotNull(); assertThat(callFailed.ioe).isNotNull();
} }
@Test public void emptyResponseBody() throws IOException { @Test public void emptyResponseBody() throws IOException {
@ -919,11 +902,10 @@ public final class EventListenerTest {
Response response = call.execute(); Response response = call.execute();
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void emptyResponseBodyConnectionClose() throws IOException { @Test public void emptyResponseBodyConnectionClose() throws IOException {
@ -937,11 +919,10 @@ public final class EventListenerTest {
Response response = call.execute(); Response response = call.execute();
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException { @Test public void responseBodyClosedClosedWithoutReadingAllData() throws IOException {
@ -956,22 +937,21 @@ public final class EventListenerTest {
Response response = call.execute(); Response response = call.execute();
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void requestBodyFailHttp1OverHttps() throws IOException { @Test public void requestBodyFailHttp1OverHttps() throws IOException {
enableTlsWithTunnel(false); enableTlsWithTunnel(false);
server.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); server.setProtocols(asList(Protocol.HTTP_1_1));
requestBodyFail(); requestBodyFail();
} }
@Test public void requestBodyFailHttp2OverHttps() throws IOException { @Test public void requestBodyFailHttp2OverHttps() throws IOException {
enableTlsWithTunnel(false); enableTlsWithTunnel(false);
server.setProtocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); server.setProtocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1));
requestBodyFail(); requestBodyFail();
} }
@ -1012,7 +992,7 @@ public final class EventListenerTest {
} }
CallFailed callFailed = listener.removeUpToEvent(CallFailed.class); CallFailed callFailed = listener.removeUpToEvent(CallFailed.class);
Assertions.assertThat(callFailed.ioe).isNotNull(); assertThat(callFailed.ioe).isNotNull();
} }
@Test public void requestBodyMultipleFailuresReportedOnlyOnce() { @Test public void requestBodyMultipleFailuresReportedOnlyOnce() {
@ -1052,22 +1032,22 @@ public final class EventListenerTest {
} catch (IOException expected) { } catch (IOException expected) {
} }
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed"); "RequestBodyStart", "RequestFailed", "ConnectionReleased", "CallFailed");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void requestBodySuccessHttp1OverHttps() throws IOException { @Test public void requestBodySuccessHttp1OverHttps() throws IOException {
enableTlsWithTunnel(false); 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), requestBodySuccess(RequestBody.create(MediaType.get("text/plain"), "Hello"), equalTo(5L),
equalTo(19L)); equalTo(19L));
} }
@Test public void requestBodySuccessHttp2OverHttps() throws IOException { @Test public void requestBodySuccessHttp2OverHttps() throws IOException {
enableTlsWithTunnel(false); 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), requestBodySuccess(RequestBody.create(MediaType.get("text/plain"), "Hello"), equalTo(5L),
equalTo(19L)); equalTo(19L));
} }
@ -1108,15 +1088,14 @@ public final class EventListenerTest {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.body().string()).isEqualTo("abc"); assertThat(response.body().string()).isEqualTo("abc");
response.body().close(); response.body().close();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
private void requestBodySuccess(RequestBody body, Matcher<Long> requestBodyBytes, private void requestBodySuccess(RequestBody body, Matcher<Long> requestBodyBytes,
@ -1128,7 +1107,7 @@ public final class EventListenerTest {
.post(body) .post(body)
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("World!"); assertThat(response.body().string()).isEqualTo("World!");
assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength, assertBytesReadWritten(listener, any(Long.class), requestBodyBytes, responseHeaderLength,
equalTo(6L)); equalTo(6L));
@ -1153,13 +1132,12 @@ public final class EventListenerTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
call.execute(); call.execute();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test @Test
@ -1172,16 +1150,15 @@ public final class EventListenerTest {
otherServer.enqueue(new MockResponse()); otherServer.enqueue(new MockResponse());
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); call.execute();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "ConnectionReleased", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ResponseBodyEnd", "ConnectionReleased", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd",
"ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
@Test public void applicationInterceptorProceedsMultipleTimes() throws Exception { @Test public void applicationInterceptorProceedsMultipleTimes() throws Exception {
@ -1191,7 +1168,7 @@ public final class EventListenerTest {
client = client.newBuilder() client = client.newBuilder()
.addInterceptor(chain -> { .addInterceptor(chain -> {
try (Response a = chain.proceed(chain.request())) { try (Response a = chain.proceed(chain.request())) {
Assertions.assertThat(a.body().string()).isEqualTo("a"); assertThat(a.body().string()).isEqualTo("a");
} }
return chain.proceed(chain.request()); return chain.proceed(chain.request());
}) })
@ -1199,18 +1176,17 @@ public final class EventListenerTest {
Call call = client.newCall(new Request.Builder().url(server.url("/")).build()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("b"); assertThat(response.body().string()).isEqualTo("b");
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "DnsStart", "DnsEnd",
"ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
"RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart",
"ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseBodyEnd", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart",
"ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased",
"CallEnd"); "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void applicationInterceptorShortCircuit() throws Exception { @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()); Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("a"); assertThat(response.body().string()).isEqualTo("a");
List<String> expectedEvents = Arrays.asList("CallStart", "CallEnd"); assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
/** Response headers start, then the entire request body, then response headers end. */ /** Response headers start, then the entire request body, then response headers end. */
@ -1246,10 +1221,10 @@ public final class EventListenerTest {
Call call = client.newCall(request); Call call = client.newCall(request);
call.execute(); call.execute();
List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd", "ConnectStart", assertThat(listener.recordedEventTypes()).containsExactly(
"CallStart", "DnsStart", "DnsEnd", "ConnectStart",
"ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd",
"ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd", "ResponseHeadersStart", "RequestBodyStart", "RequestBodyEnd", "ResponseHeadersEnd",
"ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd"); "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
Assertions.assertThat(listener.recordedEventTypes()).isEqualTo(expectedEvents);
} }
} }

View File

@ -17,7 +17,6 @@ package okhttp3;
import java.io.IOException; import java.io.IOException;
import java.time.Instant; import java.time.Instant;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -101,10 +100,10 @@ public final class HeadersTest {
.add("ping: pong ") // Value whitespace is trimmed. .add("ping: pong ") // Value whitespace is trimmed.
.add("kit:kat") // Space after colon is not required. .add("kit:kat") // Space after colon is not required.
.build(); .build();
assertThat(headers.values("foo")).isEqualTo(Arrays.asList("bar", "baz", "bak")); assertThat(headers.values("foo")).containsExactly("bar", "baz", "bak");
assertThat(headers.values("key")).isEqualTo(Arrays.asList("value")); assertThat(headers.values("key")).containsExactly("value");
assertThat(headers.values("ping")).isEqualTo(Arrays.asList("pong")); assertThat(headers.values("ping")).containsExactly("pong");
assertThat(headers.values("kit")).isEqualTo(Arrays.asList("kat")); assertThat(headers.values("kit")).containsExactly("kat");
} }
@Test public void addThrowsOnEmptyName() { @Test public void addThrowsOnEmptyName() {
@ -645,45 +644,45 @@ public final class HeadersTest {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest") .add("WWW-Authenticate", "Basic realm = \"myrealm\",Digest")
.build(); .build();
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", "myrealm")),
new Challenge("Digest", Collections.emptyMap()))); new Challenge("Digest", Collections.emptyMap()));
} }
@Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() { @Test public void multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm") .add("WWW-Authenticate", "Basic realm = \"myrealm\",Basic realm=myotherrealm")
.build(); .build();
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", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm")))); new Challenge("Basic", singletonMap("realm", "myotherrealm")));
} }
@Test public void separatorsBeforeFirstAuthParam() { @Test public void separatorsBeforeFirstAuthParam() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"") .add("WWW-Authenticate", "Digest, Basic ,,realm=\"myrealm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm")))); new Challenge("Basic", singletonMap("realm", "myrealm")));
} }
@Test public void onlyCommaBetweenChallenges() { @Test public void onlyCommaBetweenChallenges() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"") .add("WWW-Authenticate", "Digest,Basic realm=\"myrealm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm")))); new Challenge("Basic", singletonMap("realm", "myrealm")));
} }
@Test public void multipleSeparatorsBetweenChallenges() { @Test public void multipleSeparatorsBetweenChallenges() {
Headers headers = new Headers.Builder() Headers headers = new Headers.Builder()
.add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,realm=\"myrealm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm")))); new Challenge("Basic", singletonMap("realm", "myrealm")));
} }
@Test public void unknownAuthParams() { @Test public void unknownAuthParams() {
@ -694,9 +693,9 @@ public final class HeadersTest {
Map<String, String> expectedAuthParams = new LinkedHashMap<>(); Map<String, String> expectedAuthParams = new LinkedHashMap<>();
expectedAuthParams.put("realm", "myrealm"); expectedAuthParams.put("realm", "myrealm");
expectedAuthParams.put("foo", "bar"); expectedAuthParams.put("foo", "bar");
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", expectedAuthParams))); new Challenge("Basic", expectedAuthParams));
} }
@Test public void escapedCharactersInQuotedString() { @Test public void escapedCharactersInQuotedString() {
@ -704,9 +703,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\"r\\ealm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my\\\"realm")))); new Challenge("Basic", singletonMap("realm", "my\\\"realm")));
} }
@Test public void commaInQuotedStringAndBeforeFirstChallenge() { @Test public void commaInQuotedStringAndBeforeFirstChallenge() {
@ -714,9 +713,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"") .add("WWW-Authenticate", ",Digest,,,, Basic ,,,realm=\"my, realm,\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "my, realm,")))); new Challenge("Basic", singletonMap("realm", "my, realm,")));
} }
@Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() { @Test public void unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() {
@ -724,8 +723,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\\\\\\\\\"r\\ealm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()))); new Challenge("Digest", Collections.emptyMap()));
} }
@Test public void unescapedDoubleQuoteInQuotedString() { @Test public void unescapedDoubleQuoteInQuotedString() {
@ -733,8 +732,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=\"my\"realm\"")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()))); new Challenge("Digest", Collections.emptyMap()));
} }
@Ignore("TODO(jwilson): reject parameters that use invalid characters") @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") .add("WWW-Authenticate", "Digest,,,, Basic ,,,realm=my\"realm")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()))); new Challenge("Digest", Collections.emptyMap()));
} }
@Test public void token68InsteadOfAuthParams() { @Test public void token68InsteadOfAuthParams() {
@ -762,8 +761,8 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Other abc==, realm=myrealm") .add("WWW-Authenticate", "Other abc==, realm=myrealm")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Other", singletonMap(null, "abc==")))); new Challenge("Other", singletonMap(null, "abc==")));
} }
@Test public void repeatedAuthParamKey() { @Test public void repeatedAuthParamKey() {
@ -781,9 +780,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myrealm") .add("WWW-Authenticate", "Basic realm=myrealm")
.build(); .build();
assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).isEqualTo(Arrays.asList( assertThat(HttpHeaders.parseChallenges(headers, "WWW-Authenticate")).containsExactly(
new Challenge("Digest", Collections.emptyMap()), new Challenge("Digest", Collections.emptyMap()),
new Challenge("Basic", singletonMap("realm", "myrealm")))); new Challenge("Basic", singletonMap("realm", "myrealm")));
} }
@Test public void multipleAuthenticateHeadersInDifferentOrder() { @Test public void multipleAuthenticateHeadersInDifferentOrder() {
@ -792,9 +791,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Digest") .add("WWW-Authenticate", "Digest")
.build(); .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", "myrealm")),
new Challenge("Digest", Collections.emptyMap()))); new Challenge("Digest", Collections.emptyMap()));
} }
@Test public void multipleBasicAuthenticateHeaders() { @Test public void multipleBasicAuthenticateHeaders() {
@ -803,9 +802,9 @@ public final class HeadersTest {
.add("WWW-Authenticate", "Basic realm=myotherrealm") .add("WWW-Authenticate", "Basic realm=myotherrealm")
.build(); .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", "myrealm")),
new Challenge("Basic", singletonMap("realm", "myotherrealm")))); new Challenge("Basic", singletonMap("realm", "myotherrealm")));
} }
@Test public void byteCount() { @Test public void byteCount() {

View File

@ -20,7 +20,6 @@ import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashSet;
import okhttp3.UrlComponentEncodingTester.Component; import okhttp3.UrlComponentEncodingTester.Component;
import okhttp3.UrlComponentEncodingTester.Encoding; import okhttp3.UrlComponentEncodingTester.Encoding;
import org.junit.Ignore; import org.junit.Ignore;
@ -28,6 +27,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -36,7 +36,7 @@ import static org.junit.Assert.fail;
public final class HttpUrlTest { public final class HttpUrlTest {
@Parameterized.Parameters(name = "Use get = {0}") @Parameterized.Parameters(name = "Use get = {0}")
public static Collection<Object[]> parameters() { public static Collection<Object[]> parameters() {
return Arrays.asList( return asList(
new Object[] { true }, new Object[] { true },
new Object[] { false } 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/path"));
assertThat(base.newBuilder("path").build()).isEqualTo(parse("http://host/a/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("?query").build()).isEqualTo(parse("http://host/a/b?query"));
assertThat(base.newBuilder("#fragment").build()).isEqualTo( assertThat(base.newBuilder("#fragment").build())
parse("http://host/a/b#fragment")); .isEqualTo(parse("http://host/a/b#fragment"));
assertThat(base.newBuilder("").build()).isEqualTo(parse("http://host/a/b")); assertThat(base.newBuilder("").build()).isEqualTo(parse("http://host/a/b"));
assertThat(base.newBuilder("ftp://b")).isNull(); assertThat(base.newBuilder("ftp://b")).isNull();
assertThat(base.newBuilder("ht+tp://b")).isNull(); assertThat(base.newBuilder("ht+tp://b")).isNull();
@ -346,17 +346,17 @@ public final class HttpUrlTest {
} }
@Test public void usernameAndPassword() throws Exception { @Test public void usernameAndPassword() throws Exception {
assertThat(parse("http://username:password@host/path")).isEqualTo( assertThat(parse("http://username:password@host/path"))
parse("http://username:password@host/path")); .isEqualTo(parse("http://username:password@host/path"));
assertThat(parse("http://username:@host/path")).isEqualTo( assertThat(parse("http://username:@host/path"))
parse("http://username@host/path")); .isEqualTo(parse("http://username@host/path"));
} }
@Test public void passwordWithEmptyUsername() throws Exception { @Test public void passwordWithEmptyUsername() throws Exception {
// Chrome doesn't mind, but Firefox rejects URLs with empty usernames and non-empty passwords. // 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://:@host/path")).isEqualTo(parse("http://host/path"));
assertThat(parse("http://:password@@host/path").encodedPassword()).isEqualTo( assertThat(parse("http://:password@@host/path").encodedPassword())
"password%40"); .isEqualTo("password%40");
} }
@Test public void unprintableCharactersArePercentEncoded() throws Exception { @Test public void unprintableCharactersArePercentEncoded() throws Exception {
@ -455,10 +455,10 @@ public final class HttpUrlTest {
@Test public void hostIpv6AddressLeadingCompression() throws Exception { @Test public void hostIpv6AddressLeadingCompression() throws Exception {
assertThat(parse("http://[::0001]").host()).isEqualTo("::1"); assertThat(parse("http://[::0001]").host()).isEqualTo("::1");
assertThat(parse("http://[0000::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( assertThat(parse("http://[0000:0000:0000:0000:0000:0000:0000:0001]").host())
"::1"); .isEqualTo("::1");
assertThat(parse("http://[0000:0000:0000:0000:0000:0000::0001]").host()).isEqualTo( assertThat(parse("http://[0000:0000:0000:0000:0000:0000::0001]").host())
"::1"); .isEqualTo("::1");
} }
@Test public void hostIpv6AddressTrailingCompression() throws Exception { @Test public void hostIpv6AddressTrailingCompression() throws Exception {
@ -578,8 +578,8 @@ public final class HttpUrlTest {
} }
@Test public void hostIpv6CanonicalForm() throws Exception { @Test public void hostIpv6CanonicalForm() throws Exception {
assertThat(parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host()).isEqualTo( assertThat(parse("http://[abcd:ef01:2345:6789:abcd:ef01:2345:6789]/").host())
"abcd:ef01:2345:6789:abcd:ef01:2345:6789"); .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: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:c:0:0:0]/").host()).isEqualTo("a:b:0:0:c::");
assertThat(parse("http://[a:b:0:0:0:c:0:0]/").host()).isEqualTo("a:b::c:0:0"); assertThat(parse("http://[a: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://[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::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:0:0:0:2:1]/").host()).isEqualTo("2001:db8::2:1");
assertThat(parse("http://[2001:db8:0:1:1:1:1:1]/").host()).isEqualTo( assertThat(parse("http://[2001:db8:0:1:1:1:1:1]/").host())
"2001:db8:0:1:1:1:1:1"); .isEqualTo("2001:db8:0:1:1:1:1:1");
assertThat(parse("http://[2001:db8:0:0:1:0:0:1]/").host()).isEqualTo( assertThat(parse("http://[2001:db8:0:0:1:0:0:1]/").host())
"2001:db8::1:0:0:1"); .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://[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://[1:0:0:0:0:0:0:0]/").host()).isEqualTo("1::");
assertThat(parse("http://[0:0:0:0:0:0:0:1]/").host()).isEqualTo("::1"); assertThat(parse("http://[0:0:0:0:0:0:0:1]/").host()).isEqualTo("::1");
@ -605,13 +605,13 @@ public final class HttpUrlTest {
/** The builder permits square braces but does not require them. */ /** The builder permits square braces but does not require them. */
@Test public void hostIpv6Builder() throws Exception { @Test public void hostIpv6Builder() throws Exception {
HttpUrl base = parse("http://example.com/"); HttpUrl base = parse("http://example.com/");
assertThat(base.newBuilder().host("[::1]").build().toString()).isEqualTo( assertThat(base.newBuilder().host("[::1]").build().toString())
"http://[::1]/"); .isEqualTo("http://[::1]/");
assertThat(base.newBuilder().host("[::0001]").build().toString()).isEqualTo( assertThat(base.newBuilder().host("[::0001]").build().toString())
"http://[::1]/"); .isEqualTo("http://[::1]/");
assertThat(base.newBuilder().host("::1").build().toString()).isEqualTo("http://[::1]/"); assertThat(base.newBuilder().host("::1").build().toString()).isEqualTo("http://[::1]/");
assertThat(base.newBuilder().host("::0001").build().toString()).isEqualTo( assertThat(base.newBuilder().host("::0001").build().toString())
"http://[::1]/"); .isEqualTo("http://[::1]/");
} }
@Test public void hostIpv4CanonicalForm() throws Exception { @Test public void hostIpv4CanonicalForm() throws Exception {
@ -762,46 +762,38 @@ public final class HttpUrlTest {
@Test public void decodePassword() { @Test public void decodePassword() {
assertThat(parse("http://user:password@host/").password()).isEqualTo("password"); assertThat(parse("http://user:password@host/").password()).isEqualTo("password");
assertThat(parse("http://user:@host/").password()).isEqualTo(""); assertThat(parse("http://user:@host/").password()).isEqualTo("");
assertThat(parse("http://user:%F0%9F%8D%A9@host/").password()).isEqualTo( assertThat(parse("http://user:%F0%9F%8D%A9@host/").password())
"\uD83C\uDF69"); .isEqualTo("\uD83C\uDF69");
} }
@Test public void decodeSlashCharacterInDecodedPathSegment() { @Test public void decodeSlashCharacterInDecodedPathSegment() {
assertThat(parse("http://host/a%2Fb%2Fc").pathSegments()).isEqualTo( assertThat(parse("http://host/a%2Fb%2Fc").pathSegments()).containsExactly("a/b/c");
Arrays.asList("a/b/c"));
} }
@Test public void decodeEmptyPathSegments() { @Test public void decodeEmptyPathSegments() {
assertThat(parse("http://host/").pathSegments()).isEqualTo(Arrays.asList("")); assertThat(parse("http://host/").pathSegments()).containsExactly("");
} }
@Test public void percentDecode() throws Exception { @Test public void percentDecode() throws Exception {
assertThat(parse("http://host/%00").pathSegments()).isEqualTo(Arrays.asList("\u0000")); assertThat(parse("http://host/%00").pathSegments()).containsExactly("\u0000");
assertThat(parse("http://host/a/%E2%98%83/c").pathSegments()).isEqualTo( assertThat(parse("http://host/a/%E2%98%83/c").pathSegments()).containsExactly("a", "\u2603", "c");
Arrays.asList("a", "\u2603", "c")); assertThat(parse("http://host/a/%F0%9F%8D%A9/c").pathSegments()).containsExactly("a", "\uD83C\uDF69", "c");
assertThat(parse("http://host/a/%F0%9F%8D%A9/c").pathSegments()).isEqualTo( assertThat(parse("http://host/a/%62/c").pathSegments()).containsExactly("a", "b", "c");
Arrays.asList("a", "\uD83C\uDF69", "c")); assertThat(parse("http://host/a/%7A/c").pathSegments()).containsExactly("a", "z", "c");
assertThat(parse("http://host/a/%62/c").pathSegments()).isEqualTo( assertThat(parse("http://host/a/%7a/c").pathSegments()).containsExactly("a", "z", "c");
Arrays.asList("a", "b", "c"));
assertThat(parse("http://host/a/%7A/c").pathSegments()).isEqualTo(
Arrays.asList("a", "z", "c"));
assertThat(parse("http://host/a/%7a/c").pathSegments()).isEqualTo(
Arrays.asList("a", "z", "c"));
} }
@Test public void malformedPercentEncoding() { @Test public void malformedPercentEncoding() {
assertThat(parse("http://host/a%f/b").pathSegments()).isEqualTo( assertThat(parse("http://host/a%f/b").pathSegments()).containsExactly("a%f", "b");
Arrays.asList("a%f", "b")); assertThat(parse("http://host/%/b").pathSegments()).containsExactly("%", "b");
assertThat(parse("http://host/%/b").pathSegments()).isEqualTo(Arrays.asList("%", "b")); assertThat(parse("http://host/%").pathSegments()).containsExactly("%");
assertThat(parse("http://host/%").pathSegments()).isEqualTo(Arrays.asList("%")); assertThat(parse("http://github.com/%%30%30").pathSegments()).containsExactly("%00");
assertThat(parse("http://github.com/%%30%30").pathSegments()).isEqualTo(
Arrays.asList("%00"));
} }
@Test public void malformedUtf8Encoding() { @Test public void malformedUtf8Encoding() {
// Replace a partial UTF-8 sequence with the Unicode replacement character. // Replace a partial UTF-8 sequence with the Unicode replacement character.
assertThat(parse("http://host/a/%E2%98x/c").pathSegments()).isEqualTo( assertThat(parse("http://host/a/%E2%98x/c").pathSegments())
Arrays.asList("a", "\ufffdx", "c")); .containsExactly("a", "\ufffdx", "c");
} }
@Test public void incompleteUrlComposition() throws Exception { @Test public void incompleteUrlComposition() throws Exception {
@ -820,18 +812,17 @@ public final class HttpUrlTest {
} }
@Test public void builderToString() { @Test public void builderToString() {
assertThat(parse("https://host.com/path").newBuilder().toString()).isEqualTo( assertThat(parse("https://host.com/path").newBuilder().toString())
"https://host.com/path"); .isEqualTo("https://host.com/path");
} }
@Test public void incompleteBuilderToString() { @Test public void incompleteBuilderToString() {
assertThat(new HttpUrl.Builder().scheme("https").encodedPath("/path").toString()).isEqualTo( assertThat(new HttpUrl.Builder().scheme("https").encodedPath("/path").toString())
"https:///path"); .isEqualTo("https:///path");
assertThat(new HttpUrl.Builder().host("host.com").encodedPath("/path").toString()).isEqualTo( assertThat(new HttpUrl.Builder().host("host.com").encodedPath("/path").toString())
"//host.com/path"); .isEqualTo("//host.com/path");
assertThat( assertThat(new HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString())
(Object) new HttpUrl.Builder().host("host.com").encodedPath("/path").port(8080).toString()).isEqualTo( .isEqualTo("//host.com:8080/path");
"//host.com:8080/path");
} }
@Test public void minimalUrlComposition() throws Exception { @Test public void minimalUrlComposition() throws Exception {
@ -858,8 +849,8 @@ public final class HttpUrlTest {
.query("query") .query("query")
.fragment("fragment") .fragment("fragment")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://username:password@host:8080/path?query#fragment"); .isEqualTo("http://username:password@host:8080/path?query#fragment");
assertThat(url.scheme()).isEqualTo("http"); assertThat(url.scheme()).isEqualTo("http");
assertThat(url.username()).isEqualTo("username"); assertThat(url.username()).isEqualTo("username");
assertThat(url.password()).isEqualTo("password"); assertThat(url.password()).isEqualTo("password");
@ -917,13 +908,13 @@ public final class HttpUrlTest {
.query("i:\u0001@/\\?#%j") .query("i:\u0001@/\\?#%j")
.fragment("k:\u0001@/\\?#%l") .fragment("k:\u0001@/\\?#%l")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" .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")); + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l"));
assertThat(url.scheme()).isEqualTo("http"); assertThat(url.scheme()).isEqualTo("http");
assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b"); assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b");
assertThat(url.password()).isEqualTo("c:\u0001@/\\?#%d"); 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.query()).isEqualTo("i:\u0001@/\\?#%j");
assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l"); assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l");
assertThat(url.encodedUsername()).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b"); 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") .encodedQuery("i:\u0001@/\\?#%25j")
.encodedFragment("k:\u0001@/\\?#%25l") .encodedFragment("k:\u0001@/\\?#%25l")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
("http://a%3A%01%40%2F%5C%3F%23%25b:c%3A%01%40%2F%5C%3F%23%25d@ef:8080/" .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")); + "g:%01@%2F%5C%3F%23%25h?i:%01@/\\?%23%25j#k:%01@/\\?#%25l"));
assertThat(url.scheme()).isEqualTo("http"); assertThat(url.scheme()).isEqualTo("http");
assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b"); assertThat(url.username()).isEqualTo("a:\u0001@/\\?#%b");
assertThat(url.password()).isEqualTo("c:\u0001@/\\?#%d"); 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.query()).isEqualTo("i:\u0001@/\\?#%j");
assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l"); assertThat(url.fragment()).isEqualTo("k:\u0001@/\\?#%l");
assertThat(url.encodedUsername()).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b"); assertThat(url.encodedUsername()).isEqualTo("a%3A%01%40%2F%5C%3F%23%25b");
@ -968,7 +959,7 @@ public final class HttpUrlTest {
.build(); .build();
assertThat(url.toString()).isEqualTo("http://host/a%2Fb/c"); assertThat(url.toString()).isEqualTo("http://host/a%2Fb/c");
assertThat(url.encodedPath()).isEqualTo("/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 { @Test public void composeMixingPathSegments() throws Exception {
@ -981,24 +972,22 @@ public final class HttpUrlTest {
.build(); .build();
assertThat(url.toString()).isEqualTo("http://host/a%2fb/c/d%2525e/f%25g"); 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.encodedPath()).isEqualTo("/a%2fb/c/d%2525e/f%25g");
assertThat(url.encodedPathSegments()).isEqualTo( assertThat(url.encodedPathSegments()).containsExactly("a%2fb", "c", "d%2525e", "f%25g");
Arrays.asList("a%2fb", "c", "d%2525e", "f%25g")); assertThat(url.pathSegments()).containsExactly("a/b", "c", "d%25e", "f%g");
assertThat(url.pathSegments()).isEqualTo(Arrays.asList("a/b", "c", "d%25e", "f%g"));
} }
@Test public void composeWithAddSegment() throws Exception { @Test public void composeWithAddSegment() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegment("").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment("").build().encodedPath())
"/a/b/c/"); .isEqualTo("/a/b/c/");
assertThat( assertThat(base.newBuilder().addPathSegment("").addPathSegment("d").build().encodedPath())
(Object) base.newBuilder().addPathSegment("").addPathSegment("d").build().encodedPath()).isEqualTo( .isEqualTo("/a/b/c/d");
"/a/b/c/d"); assertThat(base.newBuilder().addPathSegment("..").build().encodedPath())
assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()).isEqualTo( .isEqualTo("/a/b/");
"/a/b/"); assertThat(base.newBuilder().addPathSegment("").addPathSegment("..").build().encodedPath())
assertThat(base.newBuilder().addPathSegment("").addPathSegment("..").build() .isEqualTo("/a/b/");
.encodedPath()).isEqualTo("/a/b/"); assertThat(base.newBuilder().addPathSegment("").addPathSegment("").build().encodedPath())
assertThat(base.newBuilder().addPathSegment("").addPathSegment("").build() .isEqualTo("/a/b/c/");
.encodedPath()).isEqualTo("/a/b/c/");
} }
@Test public void pathSize() throws Exception { @Test public void pathSize() throws Exception {
@ -1010,147 +999,147 @@ public final class HttpUrlTest {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
// Add a string with zero slashes: resulting URL gains one slash. // Add a string with zero slashes: resulting URL gains one slash.
assertThat(base.newBuilder().addPathSegments("").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("").build().encodedPath())
"/a/b/c/"); .isEqualTo("/a/b/c/");
assertThat(base.newBuilder().addPathSegments("d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d").build().encodedPath())
"/a/b/c/d"); .isEqualTo("/a/b/c/d");
// Add a string with one slash: resulting URL gains two slashes. // Add a string with one slash: resulting URL gains two slashes.
assertThat(base.newBuilder().addPathSegments("/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/").build().encodedPath())
"/a/b/c//"); .isEqualTo("/a/b/c//");
assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath())
"/a/b/c/d/"); .isEqualTo("/a/b/c/d/");
assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath())
"/a/b/c//d"); .isEqualTo("/a/b/c//d");
// Add a string with two slashes: resulting URL gains three slashes. // Add a string with two slashes: resulting URL gains three slashes.
assertThat(base.newBuilder().addPathSegments("//").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("//").build().encodedPath())
"/a/b/c///"); .isEqualTo("/a/b/c///");
assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath())
"/a/b/c//d/"); .isEqualTo("/a/b/c//d/");
assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath())
"/a/b/c/d//"); .isEqualTo("/a/b/c/d//");
assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath())
"/a/b/c///d"); .isEqualTo("/a/b/c///d");
assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath())
"/a/b/c/d/e/f"); .isEqualTo("/a/b/c/d/e/f");
} }
@Test public void addPathSegmentsOntoTrailingSlash() throws Exception { @Test public void addPathSegmentsOntoTrailingSlash() throws Exception {
HttpUrl base = parse("http://host/a/b/c/"); HttpUrl base = parse("http://host/a/b/c/");
// Add a string with zero slashes: resulting URL gains zero slashes. // Add a string with zero slashes: resulting URL gains zero slashes.
assertThat(base.newBuilder().addPathSegments("").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("").build().encodedPath())
"/a/b/c/"); .isEqualTo("/a/b/c/");
assertThat(base.newBuilder().addPathSegments("d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d").build().encodedPath())
"/a/b/c/d"); .isEqualTo("/a/b/c/d");
// Add a string with one slash: resulting URL gains one slash. // Add a string with one slash: resulting URL gains one slash.
assertThat(base.newBuilder().addPathSegments("/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/").build().encodedPath())
"/a/b/c//"); .isEqualTo("/a/b/c//");
assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d/").build().encodedPath())
"/a/b/c/d/"); .isEqualTo("/a/b/c/d/");
assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/d").build().encodedPath())
"/a/b/c//d"); .isEqualTo("/a/b/c//d");
// Add a string with two slashes: resulting URL gains two slashes. // Add a string with two slashes: resulting URL gains two slashes.
assertThat(base.newBuilder().addPathSegments("//").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("//").build().encodedPath())
"/a/b/c///"); .isEqualTo("/a/b/c///");
assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/d/").build().encodedPath())
"/a/b/c//d/"); .isEqualTo("/a/b/c//d/");
assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d//").build().encodedPath())
"/a/b/c/d//"); .isEqualTo("/a/b/c/d//");
assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("//d").build().encodedPath())
"/a/b/c///d"); .isEqualTo("/a/b/c///d");
assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d/e/f").build().encodedPath())
"/a/b/c/d/e/f"); .isEqualTo("/a/b/c/d/e/f");
} }
@Test public void addPathSegmentsWithBackslash() throws Exception { @Test public void addPathSegmentsWithBackslash() throws Exception {
HttpUrl base = parse("http://host/"); HttpUrl base = parse("http://host/");
assertThat(base.newBuilder().addPathSegments("d\\e").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("d\\e").build().encodedPath())
"/d/e"); .isEqualTo("/d/e");
assertThat(base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addEncodedPathSegments("d\\e").build().encodedPath())
"/d/e"); .isEqualTo("/d/e");
} }
@Test public void addPathSegmentsWithEmptyPaths() throws Exception { @Test public void addPathSegmentsWithEmptyPaths() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegments("/d/e///f").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegments("/d/e///f").build().encodedPath())
"/a/b/c//d/e///f"); .isEqualTo("/a/b/c//d/e///f");
} }
@Test public void addEncodedPathSegments() throws Exception { @Test public void addEncodedPathSegments() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat( assertThat(
(Object) base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath()).isEqualTo( (Object) base.newBuilder().addEncodedPathSegments("d/e/%20/\n").build().encodedPath())
"/a/b/c/d/e/%20/"); .isEqualTo("/a/b/c/d/e/%20/");
} }
@Test public void addPathSegmentDotDoesNothing() throws Exception { @Test public void addPathSegmentDotDoesNothing() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegment(".").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment(".").build().encodedPath())
"/a/b/c"); .isEqualTo("/a/b/c");
} }
@Test public void addPathSegmentEncodes() throws Exception { @Test public void addPathSegmentEncodes() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegment("%2e").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment("%2e").build().encodedPath())
"/a/b/c/%252e"); .isEqualTo("/a/b/c/%252e");
assertThat(base.newBuilder().addPathSegment("%2e%2e").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment("%2e%2e").build().encodedPath())
"/a/b/c/%252e%252e"); .isEqualTo("/a/b/c/%252e%252e");
} }
@Test public void addPathSegmentDotDotPopsDirectory() throws Exception { @Test public void addPathSegmentDotDotPopsDirectory() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegment("..").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment("..").build().encodedPath())
"/a/b/"); .isEqualTo("/a/b/");
} }
@Test public void addPathSegmentDotAndIgnoredCharacter() throws Exception { @Test public void addPathSegmentDotAndIgnoredCharacter() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addPathSegment(".\n").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addPathSegment(".\n").build().encodedPath())
"/a/b/c/.%0A"); .isEqualTo("/a/b/c/.%0A");
} }
@Test public void addEncodedPathSegmentDotAndIgnoredCharacter() throws Exception { @Test public void addEncodedPathSegmentDotAndIgnoredCharacter() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addEncodedPathSegment(".\n").build().encodedPath())
"/a/b/c"); .isEqualTo("/a/b/c");
} }
@Test public void addEncodedPathSegmentDotDotAndIgnoredCharacter() throws Exception { @Test public void addEncodedPathSegmentDotDotAndIgnoredCharacter() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().addEncodedPathSegment("..\n").build().encodedPath())
"/a/b/"); .isEqualTo("/a/b/");
} }
@Test public void setPathSegment() throws Exception { @Test public void setPathSegment() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().setPathSegment(0, "d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(0, "d").build().encodedPath())
"/d/b/c"); .isEqualTo("/d/b/c");
assertThat(base.newBuilder().setPathSegment(1, "d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(1, "d").build().encodedPath())
"/a/d/c"); .isEqualTo("/a/d/c");
assertThat(base.newBuilder().setPathSegment(2, "d").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(2, "d").build().encodedPath())
"/a/b/d"); .isEqualTo("/a/b/d");
} }
@Test public void setPathSegmentEncodes() throws Exception { @Test public void setPathSegmentEncodes() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().setPathSegment(0, "%25").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(0, "%25").build().encodedPath())
"/%2525/b/c"); .isEqualTo("/%2525/b/c");
assertThat(base.newBuilder().setPathSegment(0, ".\n").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(0, ".\n").build().encodedPath())
"/.%0A/b/c"); .isEqualTo("/.%0A/b/c");
assertThat(base.newBuilder().setPathSegment(0, "%2e").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(0, "%2e").build().encodedPath())
"/%252e/b/c"); .isEqualTo("/%252e/b/c");
} }
@Test public void setPathSegmentAcceptsEmpty() throws Exception { @Test public void setPathSegmentAcceptsEmpty() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().setPathSegment(0, "").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(0, "").build().encodedPath())
"//b/c"); .isEqualTo("//b/c");
assertThat(base.newBuilder().setPathSegment(2, "").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setPathSegment(2, "").build().encodedPath())
"/a/b/"); .isEqualTo("/a/b/");
} }
@Test public void setPathSegmentRejectsDot() throws Exception { @Test public void setPathSegmentRejectsDot() throws Exception {
@ -1187,8 +1176,8 @@ public final class HttpUrlTest {
@Test public void setEncodedPathSegmentEncodes() throws Exception { @Test public void setEncodedPathSegmentEncodes() throws Exception {
HttpUrl base = parse("http://host/a/b/c"); HttpUrl base = parse("http://host/a/b/c");
assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath()).isEqualTo( assertThat(base.newBuilder().setEncodedPathSegment(0, "%25").build().encodedPath())
"/%25/b/c"); .isEqualTo("/%25/b/c");
} }
@Test public void setEncodedPathSegmentRejectsDot() throws Exception { @Test public void setEncodedPathSegmentRejectsDot() throws Exception {
@ -1256,7 +1245,7 @@ public final class HttpUrlTest {
.removePathSegment(0) .removePathSegment(0)
.removePathSegment(0) .removePathSegment(0)
.build(); .build();
assertThat(url.pathSegments()).isEqualTo(Arrays.asList("")); assertThat(url.pathSegments()).containsExactly("");
assertThat(url.encodedPath()).isEqualTo("/"); assertThat(url.encodedPath()).isEqualTo("/");
} }
@ -1271,15 +1260,15 @@ public final class HttpUrlTest {
@Test public void toJavaNetUrl() throws Exception { @Test public void toJavaNetUrl() throws Exception {
HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment");
URL javaNetUrl = httpUrl.url(); URL javaNetUrl = httpUrl.url();
assertThat(javaNetUrl.toString()).isEqualTo( assertThat(javaNetUrl.toString())
"http://username:password@host/path?query#fragment"); .isEqualTo("http://username:password@host/path?query#fragment");
} }
@Test public void toUri() throws Exception { @Test public void toUri() throws Exception {
HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment"); HttpUrl httpUrl = parse("http://username:password@host/path?query#fragment");
URI uri = httpUrl.uri(); URI uri = httpUrl.uri();
assertThat(uri.toString()).isEqualTo( assertThat(uri.toString())
"http://username:password@host/path?query#fragment"); .isEqualTo("http://username:password@host/path?query#fragment");
} }
@Test public void toUriSpecialQueryCharacters() throws Exception { @Test public void toUriSpecialQueryCharacters() throws Exception {
@ -1304,10 +1293,10 @@ public final class HttpUrlTest {
.host("host") .host("host")
.username("=[]:;\"~|?#@^/$%*") .username("=[]:;\"~|?#@^/$%*")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); .isEqualTo("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/");
assertThat(url.uri().toString()).isEqualTo( assertThat(url.uri().toString())
"http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); .isEqualTo("http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/");
} }
@Test public void toUriPasswordSpecialCharacters() throws Exception { @Test public void toUriPasswordSpecialCharacters() throws Exception {
@ -1317,10 +1306,10 @@ public final class HttpUrlTest {
.username("user") .username("user")
.password("=[]:;\"~|?#@^/$%*") .password("=[]:;\"~|?#@^/$%*")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); .isEqualTo("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/");
assertThat(url.uri().toString()).isEqualTo( assertThat(url.uri().toString())
"http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/"); .isEqualTo("http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/");
} }
@Test public void toUriPathSpecialCharacters() throws Exception { @Test public void toUriPathSpecialCharacters() throws Exception {
@ -1330,8 +1319,8 @@ public final class HttpUrlTest {
.addPathSegment("=[]:;\"~|?#@^/$%*") .addPathSegment("=[]:;\"~|?#@^/$%*")
.build(); .build();
assertThat(url.toString()).isEqualTo("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*"); assertThat(url.toString()).isEqualTo("http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*");
assertThat(url.uri().toString()).isEqualTo( assertThat(url.uri().toString())
"http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*"); .isEqualTo("http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*");
} }
@Test public void toUriQueryParameterNameSpecialCharacters() throws Exception { @Test public void toUriQueryParameterNameSpecialCharacters() throws Exception {
@ -1340,10 +1329,10 @@ public final class HttpUrlTest {
.host("host") .host("host")
.addQueryParameter("=[]:;\"~|?#@^/$%*", "a") .addQueryParameter("=[]:;\"~|?#@^/$%*", "a")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a"); .isEqualTo("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a");
assertThat(url.uri().toString()).isEqualTo( assertThat(url.uri().toString())
"http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a"); .isEqualTo("http://host/?%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*=a");
assertThat(url.queryParameter("=[]:;\"~|?#@^/$%*")).isEqualTo("a"); assertThat(url.queryParameter("=[]:;\"~|?#@^/$%*")).isEqualTo("a");
} }
@ -1353,10 +1342,10 @@ public final class HttpUrlTest {
.host("host") .host("host")
.addQueryParameter("a", "=[]:;\"~|?#@^/$%*") .addQueryParameter("a", "=[]:;\"~|?#@^/$%*")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*"); .isEqualTo("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*");
assertThat(url.uri().toString()).isEqualTo( assertThat(url.uri().toString())
"http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*"); .isEqualTo("http://host/?a=%3D%5B%5D%3A%3B%22%7E%7C%3F%23%40%5E%2F%24%25*");
assertThat(url.queryParameter("a")).isEqualTo("=[]:;\"~|?#@^/$%*"); assertThat(url.queryParameter("a")).isEqualTo("=[]:;\"~|?#@^/$%*");
} }
@ -1376,8 +1365,8 @@ public final class HttpUrlTest {
.host("host") .host("host")
.addQueryParameter("a", "!$(),/:;?@[]\\^`{|}~") .addQueryParameter("a", "!$(),/:;?@[]\\^`{|}~")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://host/?a=%21%24%28%29%2C%2F%3A%3B%3F%40%5B%5D%5C%5E%60%7B%7C%7D%7E"); .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("!$(),/:;?@[]\\^`{|}~"); assertThat(url.queryParameter("a")).isEqualTo("!$(),/:;?@[]\\^`{|}~");
} }
@ -1418,20 +1407,20 @@ public final class HttpUrlTest {
@Test public void toUriWithControlCharacters() throws Exception { @Test public void toUriWithControlCharacters() throws Exception {
// Percent-encoded in the path. // Percent-encoded in the path.
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( assertThat(parse("http://host/a\u0080b").uri())
new URI("http://host/a%C2%80b")); .isEqualTo(new URI("http://host/a%C2%80b"));
assertThat(parse("http://host/a\u009fb").uri()).isEqualTo( assertThat(parse("http://host/a\u009fb").uri())
new URI("http://host/a%C2%9Fb")); .isEqualTo(new URI("http://host/a%C2%9Fb"));
// Percent-encoded in the query. // Percent-encoded in the query.
assertThat(parse("http://host/?a\u0000b").uri()).isEqualTo( assertThat(parse("http://host/?a\u0000b").uri())
new URI("http://host/?a%00b")); .isEqualTo(new URI("http://host/?a%00b"));
assertThat(parse("http://host/?a\u0080b").uri()).isEqualTo( assertThat(parse("http://host/?a\u0080b").uri())
new URI("http://host/?a%C2%80b")); .isEqualTo(new URI("http://host/?a%C2%80b"));
assertThat(parse("http://host/?a\u009fb").uri()).isEqualTo( assertThat(parse("http://host/?a\u009fb").uri())
new URI("http://host/?a%C2%9Fb")); .isEqualTo(new URI("http://host/?a%C2%9Fb"));
// Stripped from the fragment. // Stripped from the fragment.
assertThat(parse("http://host/#a\u0000b").uri()).isEqualTo( assertThat(parse("http://host/#a\u0000b").uri())
new URI("http://host/#a%00b")); .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\u0080b").uri()).isEqualTo(new URI("http://host/#ab"));
assertThat(parse("http://host/#a\u009fb").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. // Percent-encoded in the path.
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 b").uri()).isEqualTo(new URI("http://host/a%20b"));
assertThat(parse("http://host/a\u2009b").uri()).isEqualTo( assertThat(parse("http://host/a\u2009b").uri())
new URI("http://host/a%E2%80%89b")); .isEqualTo(new URI("http://host/a%E2%80%89b"));
assertThat(parse("http://host/a\u3000b").uri()).isEqualTo( assertThat(parse("http://host/a\u3000b").uri())
new URI("http://host/a%E3%80%80b")); .isEqualTo(new URI("http://host/a%E3%80%80b"));
// Percent-encoded in the query. // Percent-encoded in the query.
assertThat(parse("http://host/?a\u000bb").uri()).isEqualTo( assertThat(parse("http://host/?a\u000bb").uri())
new URI("http://host/?a%0Bb")); .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 b").uri()).isEqualTo(new URI("http://host/?a%20b"));
assertThat(parse("http://host/?a\u2009b").uri()).isEqualTo( assertThat(parse("http://host/?a\u2009b").uri())
new URI("http://host/?a%E2%80%89b")); .isEqualTo(new URI("http://host/?a%E2%80%89b"));
assertThat(parse("http://host/?a\u3000b").uri()).isEqualTo( assertThat(parse("http://host/?a\u3000b").uri())
new URI("http://host/?a%E3%80%80b")); .isEqualTo(new URI("http://host/?a%E3%80%80b"));
// Stripped from the fragment. // Stripped from the fragment.
assertThat(parse("http://host/#a\u000bb").uri()).isEqualTo( assertThat(parse("http://host/#a\u000bb").uri())
new URI("http://host/#a%0Bb")); .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 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\u2009b").uri()).isEqualTo(new URI("http://host/#ab"));
assertThat(parse("http://host/#a\u3000b").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 { @Test public void fromJavaNetUrl() throws Exception {
URL javaNetUrl = new URL("http://username:password@host/path?query#fragment"); URL javaNetUrl = new URL("http://username:password@host/path?query#fragment");
HttpUrl httpUrl = HttpUrl.get(javaNetUrl); HttpUrl httpUrl = HttpUrl.get(javaNetUrl);
assertThat(httpUrl.toString()).isEqualTo( assertThat(httpUrl.toString())
"http://username:password@host/path?query#fragment"); .isEqualTo("http://username:password@host/path?query#fragment");
} }
@Test public void fromJavaNetUrlUnsupportedScheme() throws Exception { @Test public void fromJavaNetUrlUnsupportedScheme() throws Exception {
@ -1484,8 +1473,8 @@ public final class HttpUrlTest {
@Test public void fromUri() throws Exception { @Test public void fromUri() throws Exception {
URI uri = new URI("http://username:password@host/path?query#fragment"); URI uri = new URI("http://username:password@host/path?query#fragment");
HttpUrl httpUrl = HttpUrl.get(uri); HttpUrl httpUrl = HttpUrl.get(uri);
assertThat(httpUrl.toString()).isEqualTo( assertThat(httpUrl.toString())
"http://username:password@host/path?query#fragment"); .isEqualTo("http://username:password@host/path?query#fragment");
} }
@Test public void fromUriUnsupportedScheme() throws Exception { @Test public void fromUriUnsupportedScheme() throws Exception {
@ -1561,12 +1550,11 @@ public final class HttpUrlTest {
.addQueryParameter("a+=& b", "c+=& d") .addQueryParameter("a+=& b", "c+=& d")
.addQueryParameter("a+=& b", "e+=& f") .addQueryParameter("a+=& b", "e+=& f")
.build(); .build();
assertThat(url.toString()).isEqualTo( assertThat(url.toString())
"http://host/?a%2B%3D%26%20b=c%2B%3D%26%20d&a%2B%3D%26%20b=e%2B%3D%26%20f"); .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.querySize()).isEqualTo(2);
assertThat(url.queryParameterNames()).isEqualTo(Collections.singleton("a+=& b")); assertThat(url.queryParameterNames()).isEqualTo(Collections.singleton("a+=& b"));
assertThat(url.queryParameterValues("a+=& b")).isEqualTo( assertThat(url.queryParameterValues("a+=& b")).containsExactly("c+=& d", "e+=& f");
Arrays.asList("c+=& d", "e+=& f"));
} }
@Test public void absentQueryIsZeroNameValuePairs() throws Exception { @Test public void absentQueryIsZeroNameValuePairs() throws Exception {
@ -1607,8 +1595,7 @@ public final class HttpUrlTest {
@Test public void queryParametersWithoutValues() throws Exception { @Test public void queryParametersWithoutValues() throws Exception {
HttpUrl url = parse("http://host/?foo&bar&baz"); HttpUrl url = parse("http://host/?foo&bar&baz");
assertThat(url.querySize()).isEqualTo(3); assertThat(url.querySize()).isEqualTo(3);
assertThat(url.queryParameterNames()).isEqualTo( assertThat(url.queryParameterNames()).containsExactly("foo", "bar", "baz");
new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")));
assertThat(url.queryParameterValue(0)).isNull(); assertThat(url.queryParameterValue(0)).isNull();
assertThat(url.queryParameterValue(1)).isNull(); assertThat(url.queryParameterValue(1)).isNull();
assertThat(url.queryParameterValue(2)).isNull(); assertThat(url.queryParameterValue(2)).isNull();
@ -1620,8 +1607,7 @@ public final class HttpUrlTest {
@Test public void queryParametersWithEmptyValues() throws Exception { @Test public void queryParametersWithEmptyValues() throws Exception {
HttpUrl url = parse("http://host/?foo=&bar=&baz="); HttpUrl url = parse("http://host/?foo=&bar=&baz=");
assertThat(url.querySize()).isEqualTo(3); assertThat(url.querySize()).isEqualTo(3);
assertThat(url.queryParameterNames()).isEqualTo( assertThat(url.queryParameterNames()).containsExactly("foo", "bar", "baz");
new LinkedHashSet<>(Arrays.asList("foo", "bar", "baz")));
assertThat(url.queryParameterValue(0)).isEqualTo(""); assertThat(url.queryParameterValue(0)).isEqualTo("");
assertThat(url.queryParameterValue(1)).isEqualTo(""); assertThat(url.queryParameterValue(1)).isEqualTo("");
assertThat(url.queryParameterValue(2)).isEqualTo(""); assertThat(url.queryParameterValue(2)).isEqualTo("");
@ -1637,7 +1623,7 @@ public final class HttpUrlTest {
assertThat(url.queryParameterValue(0)).isEqualTo("1"); assertThat(url.queryParameterValue(0)).isEqualTo("1");
assertThat(url.queryParameterValue(1)).isEqualTo("2"); assertThat(url.queryParameterValue(1)).isEqualTo("2");
assertThat(url.queryParameterValue(2)).isEqualTo("3"); 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 { @Test public void queryParameterLookupWithNonCanonicalEncoding() throws Exception {
@ -1666,8 +1652,8 @@ public final class HttpUrlTest {
.fragment("%") .fragment("%")
.build(); .build();
assertThat(url.toString()).isEqualTo("http://%25:%25@host/%25?%25#%25"); assertThat(url.toString()).isEqualTo("http://%25:%25@host/%25?%25#%25");
assertThat(url.newBuilder().build().toString()).isEqualTo( assertThat(url.newBuilder().build().toString())
"http://%25:%25@host/%25?%25#%25"); .isEqualTo("http://%25:%25@host/%25?%25#%25");
assertThat(url.resolve("").toString()).isEqualTo("http://%25:%25@host/%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.encodedUsername()).isEqualTo("%6d%6D");
assertThat(url.encodedPassword()).isEqualTo("%6d%6D"); assertThat(url.encodedPassword()).isEqualTo("%6d%6D");
assertThat(url.encodedPath()).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.encodedQuery()).isEqualTo("%6d%6D");
assertThat(url.encodedFragment()).isEqualTo("%6d%6D"); assertThat(url.encodedFragment()).isEqualTo("%6d%6D");
assertThat(url.toString()).isEqualTo(urlString); assertThat(url.toString()).isEqualTo(urlString);
assertThat(url.newBuilder().build().toString()).isEqualTo(urlString); assertThat(url.newBuilder().build().toString()).isEqualTo(urlString);
assertThat(url.resolve("").toString()).isEqualTo( assertThat(url.resolve("").toString())
"http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D"); .isEqualTo("http://%6d%6D:%6d%6D@host/%6d%6D?%6d%6D");
} }
@Test public void clearFragment() throws Exception { @Test public void clearFragment() throws Exception {
@ -1712,12 +1698,12 @@ public final class HttpUrlTest {
@Test public void topPrivateDomain() { @Test public void topPrivateDomain() {
assertThat(parse("https://google.com").topPrivateDomain()).isEqualTo("google.com"); assertThat(parse("https://google.com").topPrivateDomain()).isEqualTo("google.com");
assertThat(parse("https://adwords.google.co.uk").topPrivateDomain()).isEqualTo( assertThat(parse("https://adwords.google.co.uk").topPrivateDomain())
"google.co.uk"); .isEqualTo("google.co.uk");
assertThat(parse("https://栃.栃木.jp").topPrivateDomain()).isEqualTo( assertThat(parse("https://栃.栃木.jp").topPrivateDomain())
"xn--ewv.xn--4pvxs.jp"); .isEqualTo("xn--ewv.xn--4pvxs.jp");
assertThat(parse("https://xn--ewv.xn--4pvxs.jp").topPrivateDomain()).isEqualTo( assertThat(parse("https://xn--ewv.xn--4pvxs.jp").topPrivateDomain())
"xn--ewv.xn--4pvxs.jp"); .isEqualTo("xn--ewv.xn--4pvxs.jp");
assertThat(parse("https://co.uk").topPrivateDomain()).isNull(); assertThat(parse("https://co.uk").topPrivateDomain()).isNull();
assertThat(parse("https://square").topPrivateDomain()).isNull(); assertThat(parse("https://square").topPrivateDomain()).isNull();

View File

@ -339,12 +339,11 @@ public final class InterceptorTest {
.build(); .build();
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
assertThat(response.headers("Response-Interceptor")).isEqualTo( assertThat(response.headers("Response-Interceptor")).containsExactly("Cupcake", "Donut");
Arrays.asList("Cupcake", "Donut"));
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
assertThat(recordedRequest.getHeaders().values("Request-Interceptor")).isEqualTo( assertThat(recordedRequest.getHeaders().values("Request-Interceptor"))
Arrays.asList("Android", "Bob")); .containsExactly("Android", "Bob");
} }
@Test public void asyncApplicationInterceptors() throws Exception { @Test public void asyncApplicationInterceptors() throws Exception {

View File

@ -24,6 +24,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -37,7 +38,7 @@ import static org.junit.Assert.fail;
public class MediaTypeTest { public class MediaTypeTest {
@Parameterized.Parameters(name = "Use get = {0}") @Parameterized.Parameters(name = "Use get = {0}")
public static Collection<Object[]> parameters() { public static Collection<Object[]> parameters() {
return Arrays.asList( return asList(
new Object[] { true }, new Object[] { true },
new Object[] { false } new Object[] { false }
); );

View File

@ -28,6 +28,7 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@ -128,7 +129,7 @@ public final class OkHttpClientTest {
@Test public void setProtocolsRejectsHttp10() throws Exception { @Test public void setProtocolsRejectsHttp10() throws Exception {
OkHttpClient.Builder builder = new OkHttpClient.Builder(); OkHttpClient.Builder builder = new OkHttpClient.Builder();
try { 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(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
} }
@ -185,7 +186,7 @@ public final class OkHttpClientTest {
@Test public void testH2PriorKnowledgeOkHttpClientConstructionFallback() { @Test public void testH2PriorKnowledgeOkHttpClientConstructionFallback() {
try { try {
new OkHttpClient.Builder() 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(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo( assertThat(expected.getMessage()).isEqualTo(
@ -197,7 +198,7 @@ public final class OkHttpClientTest {
@Test public void testH2PriorKnowledgeOkHttpClientConstructionDuplicates() { @Test public void testH2PriorKnowledgeOkHttpClientConstructionDuplicates() {
try { try {
new OkHttpClient.Builder() 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(); fail();
} catch (IllegalArgumentException expected) { } catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo( assertThat(expected.getMessage()).isEqualTo(
@ -208,7 +209,7 @@ public final class OkHttpClientTest {
@Test public void testH2PriorKnowledgeOkHttpClientConstructionSuccess() { @Test public void testH2PriorKnowledgeOkHttpClientConstructionSuccess() {
OkHttpClient okHttpClient = new OkHttpClient.Builder() OkHttpClient okHttpClient = new OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)) .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE))
.build(); .build();
assertThat(okHttpClient.protocols().size()).isEqualTo(1); assertThat(okHttpClient.protocols().size()).isEqualTo(1);
assertThat(okHttpClient.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE); assertThat(okHttpClient.protocols().get(0)).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE);

View File

@ -53,7 +53,7 @@ public final class RecordedResponse {
} }
public RecordedResponse assertRequestHeader(String name, String... values) { public RecordedResponse assertRequestHeader(String name, String... values) {
assertThat(request.headers(name)).isEqualTo(Arrays.asList(values)); assertThat(request.headers(name)).containsExactly(values);
return this; return this;
} }
@ -73,7 +73,7 @@ public final class RecordedResponse {
} }
public RecordedResponse assertHeader(String name, String... values) { public RecordedResponse assertHeader(String name, String... values) {
assertThat(response.headers(name)).isEqualTo(Arrays.asList(values)); assertThat(response.headers(name)).containsExactly(values);
return this; return this;
} }
@ -148,15 +148,16 @@ public final class RecordedResponse {
break; break;
} }
} }
assertThat(found).overridingErrorMessage("Expected exception type among " + Arrays.toString(allowedExceptionTypes) assertThat(found)
+ ", got " + failure).isTrue(); .overridingErrorMessage("Expected exception type among "
+ Arrays.toString(allowedExceptionTypes) + ", got " + failure)
.isTrue();
return this; return this;
} }
public RecordedResponse assertFailure(String... messages) { public RecordedResponse assertFailure(String... messages) {
assertThat(failure).overridingErrorMessage("No failure found").isNotNull(); assertThat(failure).overridingErrorMessage("No failure found").isNotNull();
assertThat(Arrays.asList(messages).contains(failure.getMessage())).overridingErrorMessage( assertThat(messages).contains(failure.getMessage());
failure.getMessage()).isTrue();
return this; return this;
} }
@ -179,10 +180,10 @@ public final class RecordedResponse {
} }
private void assertDateInRange(long minimum, long actual, long maximum) { private void assertDateInRange(long minimum, long actual, long maximum) {
assertThat(actual >= minimum).overridingErrorMessage( assertThat(actual)
"actual " + format(actual) + " < minimum " + format(maximum)).isTrue(); .overridingErrorMessage("%s <= %s <= %s", format(minimum), format(actual), format(maximum))
assertThat(actual <= maximum).overridingErrorMessage( .isBetween(minimum, maximum);
"actual " + format(actual) + " > maximum " + format(minimum)).isTrue();
} }
private String format(long time) { private String format(long time) {

View File

@ -20,12 +20,12 @@ import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Proxy; import java.net.Proxy;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque; import java.util.Deque;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedDeque;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public final class RecordingEventListener extends EventListener { public final class RecordingEventListener extends EventListener {
@ -71,8 +71,7 @@ public final class RecordingEventListener extends EventListener {
CallEvent startEvent = e.closes(); CallEvent startEvent = e.closes();
if (startEvent != null) { if (startEvent != null) {
assertThat(eventSequence.contains(startEvent)).overridingErrorMessage( assertThat(eventSequence).contains(startEvent);
e.getName() + " without matching " + startEvent.getName()).isTrue();
} }
eventSequence.offer(e); eventSequence.offer(e);
@ -175,7 +174,7 @@ public final class RecordingEventListener extends EventListener {
CallEvent(Call call, Object... params) { CallEvent(Call call, Object... params) {
this.call = call; this.call = call;
this.params = Arrays.asList(params); this.params = asList(params);
} }
public String getName() { public String getName() {

File diff suppressed because it is too large Load Diff

View File

@ -21,6 +21,8 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import okhttp3.Dns; 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 * 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. * fallbacks to guarantee that a fallback address is available.
@ -28,6 +30,6 @@ import okhttp3.Dns;
public class DoubleInetAddressDns implements Dns { public class DoubleInetAddressDns implements Dns {
@Override public List<InetAddress> lookup(String hostname) throws UnknownHostException { @Override public List<InetAddress> lookup(String hostname) throws UnknownHostException {
List<InetAddress> addresses = Dns.SYSTEM.lookup(hostname); List<InetAddress> addresses = Dns.SYSTEM.lookup(hostname);
return Arrays.asList(addresses.get(0), addresses.get(0)); return asList(addresses.get(0), addresses.get(0));
} }
} }

View File

@ -19,7 +19,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque; import java.util.Deque;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -38,6 +37,7 @@ import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.rules.Timeout; 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;
import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE_BACKUP; import static okhttp3.internal.cache.DiskLruCache.JOURNAL_FILE_BACKUP;
import static okhttp3.internal.cache.DiskLruCache.MAGIC; import static okhttp3.internal.cache.DiskLruCache.MAGIC;
@ -1650,7 +1650,7 @@ public final class DiskLruCacheTest {
expectedLines.add("100"); expectedLines.add("100");
expectedLines.add("2"); expectedLines.add("2");
expectedLines.add(""); expectedLines.add("");
expectedLines.addAll(Arrays.asList(expectedBodyLines)); expectedLines.addAll(asList(expectedBodyLines));
assertThat(readJournalLines()).isEqualTo(expectedLines); assertThat(readJournalLines()).isEqualTo(expectedLines);
} }

View File

@ -18,8 +18,6 @@ package okhttp3.internal.connection;
import java.io.IOException; import java.io.IOException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
import okhttp3.ConnectionSpec; import okhttp3.ConnectionSpec;
@ -28,6 +26,7 @@ import okhttp3.internal.Internal;
import okhttp3.tls.HandshakeCertificates; import okhttp3.tls.HandshakeCertificates;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -118,7 +117,7 @@ public class ConnectionSpecSelectorTest {
private static ConnectionSpecSelector createConnectionSpecSelector( private static ConnectionSpecSelector createConnectionSpecSelector(
ConnectionSpec... connectionSpecs) { ConnectionSpec... connectionSpecs) {
return new ConnectionSpecSelector(Arrays.asList(connectionSpecs)); return new ConnectionSpecSelector(asList(connectionSpecs));
} }
private SSLSocket createSocketWithEnabledProtocols(TlsVersion... tlsVersions) throws IOException { private SSLSocket createSocketWithEnabledProtocols(TlsVersion... tlsVersions) throws IOException {
@ -128,9 +127,7 @@ public class ConnectionSpecSelectorTest {
} }
private static void assertEnabledProtocols(SSLSocket socket, TlsVersion... required) { private static void assertEnabledProtocols(SSLSocket socket, TlsVersion... required) {
Set<String> actual = new LinkedHashSet<>(Arrays.asList(socket.getEnabledProtocols())); assertThat(socket.getEnabledProtocols()).containsExactlyInAnyOrder(javaNames(required));
Set<String> expected = new LinkedHashSet<>(Arrays.asList(javaNames(required)));
assertThat(actual).isEqualTo(expected);
} }
private static String[] javaNames(TlsVersion... tlsVersions) { private static String[] javaNames(TlsVersion... tlsVersions) {

View File

@ -39,7 +39,7 @@ public final class RecordingProxySelector extends ProxySelector {
} }
public void assertRequests(URI... expectedUris) { public void assertRequests(URI... expectedUris) {
assertThat(requestedUris).isEqualTo(Arrays.asList(expectedUris)); assertThat(requestedUris).containsExactly(expectedUris);
requestedUris.clear(); requestedUris.clear();
} }

View File

@ -92,7 +92,7 @@ public final class FrameLogTest {
List<String> formattedFlags = new ArrayList<>(0x40); // Highest valid flag is 0x20. List<String> formattedFlags = new ArrayList<>(0x40); // Highest valid flag is 0x20.
for (byte i = 0; i < 0x40; i++) formattedFlags.add(Http2.formatFlags(TYPE_HEADERS, i)); for (byte i = 0; i < 0x40; i++) formattedFlags.add(Http2.formatFlags(TYPE_HEADERS, i));
assertThat(formattedFlags).isEqualTo(Arrays.asList( assertThat(formattedFlags).containsExactly(
"", "",
"END_STREAM", "END_STREAM",
"00000010", "00000010",
@ -157,6 +157,6 @@ public final class FrameLogTest {
"00111101", "00111101",
"00111110", "00111110",
"00111111" "00111111"
)); );
} }
} }

View File

@ -23,6 +23,7 @@ import okio.ByteString;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static okio.ByteString.decodeHex; import static okio.ByteString.decodeHex;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -497,8 +498,8 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo( assertThat(hpackReader.getAndResetHeaderList())
Arrays.asList(new Header("www-authenticate", "Basic"))); .containsExactly(new Header("www-authenticate", "Basic"));
} }
@Test public void readLiteralHeaderWithIncrementalIndexingDynamicName() throws IOException { @Test public void readLiteralHeaderWithIncrementalIndexingDynamicName() throws IOException {
@ -514,8 +515,8 @@ public final class HpackTest {
hpackReader.readHeaders(); hpackReader.readHeaders();
assertThat(hpackReader.getAndResetHeaderList()).isEqualTo( assertThat(hpackReader.getAndResetHeaderList()).containsExactly(
Arrays.asList(new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2"))); new Header("custom-foo", "Basic"), new Header("custom-foo", "Basic2"));
} }
/** /**
@ -850,7 +851,7 @@ public final class HpackTest {
} }
@Test public void lowercaseHeaderNameBeforeEmit() throws IOException { @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'); assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'B', 'a', 'R');
} }
@ -872,26 +873,26 @@ public final class HpackTest {
@Test public void emitsDynamicTableSizeUpdate() throws IOException { @Test public void emitsDynamicTableSizeUpdate() throws IOException {
hpackWriter.setHeaderTableSizeSetting(2048); hpackWriter.setHeaderTableSizeSetting(2048);
hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); hpackWriter.writeHeaders(asList(new Header("foo", "bar")));
assertBytes( assertBytes(
0x3F, 0xE1, 0xF, // Dynamic table size update (size = 2048). 0x3F, 0xE1, 0xF, // Dynamic table size update (size = 2048).
0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r'); 0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r');
hpackWriter.setHeaderTableSizeSetting(8192); hpackWriter.setHeaderTableSizeSetting(8192);
hpackWriter.writeHeaders(Arrays.asList(new Header("bar", "foo"))); hpackWriter.writeHeaders(asList(new Header("bar", "foo")));
assertBytes( assertBytes(
0x3F, 0xE1, 0x3F, // Dynamic table size update (size = 8192). 0x3F, 0xE1, 0x3F, // Dynamic table size update (size = 8192).
0x40, 3, 'b', 'a', 'r', 3, 'f', 'o', 'o'); 0x40, 3, 'b', 'a', 'r', 3, 'f', 'o', 'o');
// No more dynamic table updates should be emitted. // 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'); assertBytes(0x40, 3, 'f', 'a', 'r', 3, 'b', 'o', 'o');
} }
@Test public void noDynamicTableSizeUpdateWhenSizeIsEqual() throws IOException { @Test public void noDynamicTableSizeUpdateWhenSizeIsEqual() throws IOException {
int currentSize = hpackWriter.headerTableSizeSetting; int currentSize = hpackWriter.headerTableSizeSetting;
hpackWriter.setHeaderTableSizeSetting(currentSize); 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'); assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r');
} }
@ -899,7 +900,7 @@ public final class HpackTest {
@Test public void growDynamicTableSize() throws IOException { @Test public void growDynamicTableSize() throws IOException {
hpackWriter.setHeaderTableSizeSetting(8192); hpackWriter.setHeaderTableSizeSetting(8192);
hpackWriter.setHeaderTableSizeSetting(16384); hpackWriter.setHeaderTableSizeSetting(16384);
hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); hpackWriter.writeHeaders(asList(new Header("foo", "bar")));
assertBytes( assertBytes(
0x3F, 0xE1, 0x7F, // Dynamic table size update (size = 16384). 0x3F, 0xE1, 0x7F, // Dynamic table size update (size = 16384).
@ -909,7 +910,7 @@ public final class HpackTest {
@Test public void shrinkDynamicTableSize() throws IOException { @Test public void shrinkDynamicTableSize() throws IOException {
hpackWriter.setHeaderTableSizeSetting(2048); hpackWriter.setHeaderTableSizeSetting(2048);
hpackWriter.setHeaderTableSizeSetting(0); hpackWriter.setHeaderTableSizeSetting(0);
hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); hpackWriter.writeHeaders(asList(new Header("foo", "bar")));
assertBytes( assertBytes(
0x20, // Dynamic size update (size = 0). 0x20, // Dynamic size update (size = 0).
@ -922,7 +923,7 @@ public final class HpackTest {
hpackWriter.setHeaderTableSizeSetting(0); hpackWriter.setHeaderTableSizeSetting(0);
hpackWriter.setHeaderTableSizeSetting(4096); hpackWriter.setHeaderTableSizeSetting(4096);
hpackWriter.setHeaderTableSizeSetting(2048); hpackWriter.setHeaderTableSizeSetting(2048);
hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar"))); hpackWriter.writeHeaders(asList(new Header("foo", "bar")));
assertBytes( assertBytes(
0x20, // Dynamic size update (size = 0). 0x20, // Dynamic size update (size = 0).

View File

@ -44,6 +44,7 @@ import org.junit.rules.TestRule;
import org.junit.rules.Timeout; import org.junit.rules.Timeout;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static okhttp3.TestUtil.repeat; import static okhttp3.TestUtil.repeat;
import static okhttp3.internal.Internal.initializeInstanceForTests; import static okhttp3.internal.Internal.initializeInstanceForTests;
@ -330,9 +331,9 @@ public final class Http2ConnectionTest {
assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold);
} }
// connection // connection
assertThat(windowUpdateStreamIds.contains(0)).isTrue(); assertThat(windowUpdateStreamIds).contains(0);
// stream // stream
assertThat(windowUpdateStreamIds.contains(3)).isTrue(); assertThat(windowUpdateStreamIds).contains(3);
} }
} }
@ -414,14 +415,14 @@ public final class Http2ConnectionTest {
peer.acceptFrame(); // ACK peer.acceptFrame(); // ACK
peer.acceptFrame(); // SYN_STREAM peer.acceptFrame(); // SYN_STREAM
peer.sendFrame().headers(false, 3, headerEntries("a", "android")); peer.sendFrame().headers(false, 3, headerEntries("a", "android"));
final List<Header> expectedRequestHeaders = Arrays.asList( final List<Header> expectedRequestHeaders = asList(
new Header(Header.TARGET_METHOD, "GET"), new Header(Header.TARGET_METHOD, "GET"),
new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_SCHEME, "https"),
new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_AUTHORITY, "squareup.com"),
new Header(Header.TARGET_PATH, "/cached") new Header(Header.TARGET_PATH, "/cached")
); );
peer.sendFrame().pushPromise(3, 2, expectedRequestHeaders); peer.sendFrame().pushPromise(3, 2, expectedRequestHeaders);
final List<Header> expectedResponseHeaders = Arrays.asList( final List<Header> expectedResponseHeaders = asList(
new Header(Header.RESPONSE_STATUS, "200") new Header(Header.RESPONSE_STATUS, "200")
); );
peer.sendFrame().headers(true, 2, expectedResponseHeaders); peer.sendFrame().headers(true, 2, expectedResponseHeaders);
@ -465,13 +466,13 @@ public final class Http2ConnectionTest {
// write the mocking script // write the mocking script
peer.sendFrame().settings(new Settings()); peer.sendFrame().settings(new Settings());
peer.acceptFrame(); // ACK 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_METHOD, "GET"),
new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_SCHEME, "https"),
new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_AUTHORITY, "squareup.com"),
new Header(Header.TARGET_PATH, "/cached") 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") new Header(Header.RESPONSE_STATUS, "200")
)); ));
peer.acceptFrame(); // RST_STREAM peer.acceptFrame(); // RST_STREAM
@ -830,8 +831,8 @@ public final class Http2ConnectionTest {
long pingAtNanos = System.nanoTime(); long pingAtNanos = System.nanoTime();
connection.writePingAndAwaitPong(); connection.writePingAndAwaitPong();
long elapsedNanos = System.nanoTime() - pingAtNanos; long elapsedNanos = System.nanoTime() - pingAtNanos;
assertThat(elapsedNanos > 0).isTrue(); assertThat(elapsedNanos).isGreaterThan(0L);
assertThat(elapsedNanos < TimeUnit.SECONDS.toNanos(1)).isTrue(); assertThat(elapsedNanos).isLessThan(TimeUnit.SECONDS.toNanos(1));
// verify the peer received what was expected // verify the peer received what was expected
InFrame pingFrame = peer.takeFrame(); InFrame pingFrame = peer.takeFrame();
@ -1660,9 +1661,9 @@ public final class Http2ConnectionTest {
assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold); assertThat(windowUpdate.windowSizeIncrement).isEqualTo(windowUpdateThreshold);
} }
// connection // connection
assertThat(windowUpdateStreamIds.contains(0)).isTrue(); assertThat(windowUpdateStreamIds).contains(0);
// stream // stream
assertThat(windowUpdateStreamIds.contains(3)).isTrue(); assertThat(windowUpdateStreamIds).contains(3);
} }
} }

View File

@ -28,6 +28,7 @@ import okio.GzipSink;
import okio.Okio; import okio.Okio;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.headerEntries; import static okhttp3.TestUtil.headerEntries;
import static okhttp3.internal.http2.Http2.FLAG_COMPRESSED; import static okhttp3.internal.http2.Http2.FLAG_COMPRESSED;
import static okhttp3.internal.http2.Http2.FLAG_END_HEADERS; import static okhttp3.internal.http2.Http2.FLAG_END_HEADERS;
@ -145,7 +146,7 @@ public final class Http2Test {
@Test public void pushPromise() throws IOException { @Test public void pushPromise() throws IOException {
final int expectedPromisedStreamId = 11; final int expectedPromisedStreamId = 11;
final List<Header> pushPromise = Arrays.asList( final List<Header> pushPromise = asList(
new Header(Header.TARGET_METHOD, "GET"), new Header(Header.TARGET_METHOD, "GET"),
new Header(Header.TARGET_SCHEME, "https"), new Header(Header.TARGET_SCHEME, "https"),
new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_AUTHORITY, "squareup.com"),

View File

@ -65,8 +65,8 @@ import okio.Buffer;
import okio.BufferedSink; import okio.BufferedSink;
import okio.GzipSink; import okio.GzipSink;
import okio.Okio; import okio.Okio;
import org.assertj.core.api.Assertions;
import org.junit.After; import org.junit.After;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
@ -78,13 +78,14 @@ import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.Parameters;
import static java.nio.charset.StandardCharsets.UTF_8; 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.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static okhttp3.tls.internal.TlsUtil.localhost; import static okhttp3.tls.internal.TlsUtil.localhost;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset; import static org.assertj.core.data.Offset.offset;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
@ -96,7 +97,7 @@ public final class HttpOverHttp2Test {
@Parameters(name = "{0}") @Parameters(name = "{0}")
public static Collection<Protocol> data() { public static Collection<Protocol> 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(); @Rule public final TemporaryFolder tempDir = new TemporaryFolder();
@ -119,13 +120,13 @@ public final class HttpOverHttp2Test {
private OkHttpClient buildH2PriorKnowledgeClient() { private OkHttpClient buildH2PriorKnowledgeClient() {
return clientTestRule.client.newBuilder() return clientTestRule.client.newBuilder()
.protocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)) .protocols(asList(Protocol.H2_PRIOR_KNOWLEDGE))
.build(); .build();
} }
private OkHttpClient buildHttp2Client() { private OkHttpClient buildHttp2Client() {
return clientTestRule.client.newBuilder() return clientTestRule.client.newBuilder()
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)) .protocols(asList(Protocol.HTTP_2, Protocol.HTTP_1_1))
.sslSocketFactory( .sslSocketFactory(
handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager()) handshakeCertificates.sslSocketFactory(), handshakeCertificates.trustManager())
.hostnameVerifier(new RecordingHostnameVerifier()) .hostnameVerifier(new RecordingHostnameVerifier())
@ -134,7 +135,7 @@ public final class HttpOverHttp2Test {
@Before public void setUp() { @Before public void setUp() {
if (protocol == Protocol.H2_PRIOR_KNOWLEDGE) { if (protocol == Protocol.H2_PRIOR_KNOWLEDGE) {
server.setProtocols(Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)); server.setProtocols(asList(Protocol.H2_PRIOR_KNOWLEDGE));
} else { } else {
server.useHttps(handshakeCertificates.sslSocketFactory(), false); server.useHttps(handshakeCertificates.sslSocketFactory(), false);
} }
@ -162,15 +163,15 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo(""); assertThat(response.message()).isEqualTo("");
Assertions.assertThat(response.protocol()).isEqualTo(protocol); assertThat(response.protocol()).isEqualTo(protocol);
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo( assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort())); (server.getHostName() + ":" + server.getPort()));
} }
@ -182,7 +183,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().byteStream().read()).isEqualTo(-1); assertThat(response.body().byteStream().read()).isEqualTo(-1);
response.body().close(); response.body().close();
} }
@ -205,12 +206,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); 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()); assertArrayEquals(postBytes, request.getBody().readByteArray());
Assertions.assertThat(request.getHeader("Content-Length")).isNull(); assertThat(request.getHeader("Content-Length")).isNull();
} }
@Test public void userSuppliedContentLengthHeader() throws Exception { @Test public void userSuppliedContentLengthHeader() throws Exception {
@ -236,12 +237,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); 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()); 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); (long) postBytes.length);
} }
@ -270,12 +271,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
RecordedRequest request = server.takeRequest(); 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()); 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); (long) postBytes.length);
} }
@ -292,12 +293,12 @@ public final class HttpOverHttp2Test {
Response response1 = call1.execute(); Response response1 = call1.execute();
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("ABC"); assertThat(response1.body().source().readUtf8(3)).isEqualTo("ABC");
Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("GHI"); assertThat(response2.body().source().readUtf8(3)).isEqualTo("GHI");
Assertions.assertThat(response1.body().source().readUtf8(3)).isEqualTo("DEF"); assertThat(response1.body().source().readUtf8(3)).isEqualTo("DEF");
Assertions.assertThat(response2.body().source().readUtf8(3)).isEqualTo("JKL"); assertThat(response2.body().source().readUtf8(3)).isEqualTo("JKL");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
response1.close(); response1.close();
response2.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 // Cancel the call and discard what we've buffered for the response body. This should free up
// the connection flow-control window so new requests can proceed. // the connection flow-control window so new requests can proceed.
call1.cancel(); call1.cancel();
Assertions.assertThat(Util.discard(response1.body().source(), 1, TimeUnit.SECONDS)).overridingErrorMessage( assertThat(Util.discard(response1.body().source(), 1, TimeUnit.SECONDS))
"Call should not have completed successfully.").isFalse(); .overridingErrorMessage("Call should not have completed successfully.")
.isFalse();
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("abc"); assertThat(response2.body().string()).isEqualTo("abc");
} }
/** Wait for the client to receive {@code dataLength} DATA frames. */ /** Wait for the client to receive {@code dataLength} DATA frames. */
@ -363,7 +365,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("abc"); assertThat(response2.body().string()).isEqualTo("abc");
} }
@Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception { @Test public void concurrentRequestWithEmptyFlowControlWindow() throws Exception {
@ -379,10 +381,10 @@ public final class HttpOverHttp2Test {
waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE); waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE);
Assertions.assertThat(response1.body().contentLength()).isEqualTo( assertThat(response1.body().contentLength()).isEqualTo(
(long) Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE); (long) Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE);
int read = response1.body().source().read(new byte[8192]); 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 // Make a second call that should transmit the response headers. The response body won't be
// transmitted until the flow-control window is updated from the first request. // transmitted until the flow-control window is updated from the first request.
@ -390,13 +392,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); 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 // Close the response body. This should discard the buffered data and update the connection
// flow-control window. // flow-control window.
response1.close(); response1.close();
Assertions.assertThat(response2.body().string()).isEqualTo("abc"); assertThat(response2.body().string()).isEqualTo("abc");
} }
/** https://github.com/square/okhttp/issues/373 */ /** 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("/r1", countDownLatch));
executor.execute(new AsyncRequest("/r2", countDownLatch)); executor.execute(new AsyncRequest("/r2", countDownLatch));
countDownLatch.await(); countDownLatch.await();
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void gzippedResponseBody() throws Exception { @Test public void gzippedResponseBody() throws Exception {
@ -423,7 +425,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCABCABC"); assertThat(response.body().string()).isEqualTo("ABCABCABC");
} }
@Test public void authenticate() throws Exception { @Test public void authenticate() throws Exception {
@ -443,13 +445,13 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("Successful auth!"); assertThat(response.body().string()).isEqualTo("Successful auth!");
RecordedRequest denied = server.takeRequest(); RecordedRequest denied = server.takeRequest();
Assertions.assertThat(denied.getHeader("Authorization")).isNull(); assertThat(denied.getHeader("Authorization")).isNull();
RecordedRequest accepted = server.takeRequest(); RecordedRequest accepted = server.takeRequest();
Assertions.assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1"); assertThat(accepted.getRequestLine()).isEqualTo("GET / HTTP/1.1");
Assertions.assertThat(accepted.getHeader("Authorization")).isEqualTo(credential); assertThat(accepted.getHeader("Authorization")).isEqualTo(credential);
} }
@Test public void redirect() throws Exception { @Test public void redirect() throws Exception {
@ -463,12 +465,12 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); 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(); RecordedRequest request1 = server.takeRequest();
Assertions.assertThat(request1.getPath()).isEqualTo("/"); assertThat(request1.getPath()).isEqualTo("/");
RecordedRequest request2 = server.takeRequest(); RecordedRequest request2 = server.takeRequest();
Assertions.assertThat(request2.getPath()).isEqualTo("/foo"); assertThat(request2.getPath()).isEqualTo("/foo");
} }
@Test public void readAfterLastByte() throws Exception { @Test public void readAfterLastByte() throws Exception {
@ -480,11 +482,11 @@ public final class HttpOverHttp2Test {
Response response = call.execute(); Response response = call.execute();
InputStream in = response.body().byteStream(); InputStream in = response.body().byteStream();
Assertions.assertThat(in.read()).isEqualTo('A'); assertThat(in.read()).isEqualTo('A');
Assertions.assertThat(in.read()).isEqualTo('B'); assertThat(in.read()).isEqualTo('B');
Assertions.assertThat(in.read()).isEqualTo('C'); assertThat(in.read()).isEqualTo('C');
Assertions.assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1);
Assertions.assertThat(in.read()).isEqualTo(-1); assertThat(in.read()).isEqualTo(-1);
in.close(); in.close();
} }
@ -505,7 +507,7 @@ public final class HttpOverHttp2Test {
call1.execute(); call1.execute();
fail("Should have timed out!"); fail("Should have timed out!");
} catch (SocketTimeoutException expected) { } catch (SocketTimeoutException expected) {
Assertions.assertThat(expected.getMessage()).isEqualTo("timeout"); assertThat(expected.getMessage()).isEqualTo("timeout");
} }
// Confirm that a subsequent request on the same connection is not impacted. // Confirm that a subsequent request on the same connection is not impacted.
@ -513,11 +515,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("A"); assertThat(response2.body().string()).isEqualTo("A");
// Confirm that the connection was reused. // Confirm that the connection was reused.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
/** /**
@ -540,7 +542,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); 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(); response1.body().string();
fail("Should have timed out!"); fail("Should have timed out!");
} catch (SocketTimeoutException expected) { } 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. // Confirm that a subsequent request on the same connection is not impacted.
@ -578,11 +580,11 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo(body); assertThat(response2.body().string()).isEqualTo(body);
// Confirm that the connection was reused. // Confirm that the connection was reused.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void connectionTimeout() throws Exception { @Test public void connectionTimeout() throws Exception {
@ -607,7 +609,7 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.body().string()).isEqualTo("A"); assertThat(response1.body().string()).isEqualTo("A");
try { try {
call2.execute(); call2.execute();
@ -616,8 +618,8 @@ public final class HttpOverHttp2Test {
} }
// Confirm that the connection was reused. // Confirm that the connection was reused.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void responsesAreCached() throws IOException { @Test public void responsesAreCached() throws IOException {
@ -634,26 +636,26 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.body().string()).isEqualTo("A"); assertThat(response1.body().string()).isEqualTo("A");
Assertions.assertThat(cache.requestCount()).isEqualTo(1); assertThat(cache.requestCount()).isEqualTo(1);
Assertions.assertThat(cache.networkCount()).isEqualTo(1); assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(0); assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("A"); assertThat(response2.body().string()).isEqualTo("A");
Call call3 = client.newCall(new Request.Builder() Call call3 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response3 = call3.execute(); Response response3 = call3.execute();
Assertions.assertThat(response3.body().string()).isEqualTo("A"); assertThat(response3.body().string()).isEqualTo("A");
Assertions.assertThat(cache.requestCount()).isEqualTo(3); assertThat(cache.requestCount()).isEqualTo(3);
Assertions.assertThat(cache.networkCount()).isEqualTo(1); assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(2); assertThat(cache.hitCount()).isEqualTo(2);
} }
@Test public void conditionalCache() throws IOException { @Test public void conditionalCache() throws IOException {
@ -671,21 +673,21 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.body().string()).isEqualTo("A"); assertThat(response1.body().string()).isEqualTo("A");
Assertions.assertThat(cache.requestCount()).isEqualTo(1); assertThat(cache.requestCount()).isEqualTo(1);
Assertions.assertThat(cache.networkCount()).isEqualTo(1); assertThat(cache.networkCount()).isEqualTo(1);
Assertions.assertThat(cache.hitCount()).isEqualTo(0); assertThat(cache.hitCount()).isEqualTo(0);
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("A"); assertThat(response2.body().string()).isEqualTo("A");
Assertions.assertThat(cache.requestCount()).isEqualTo(2); assertThat(cache.requestCount()).isEqualTo(2);
Assertions.assertThat(cache.networkCount()).isEqualTo(2); assertThat(cache.networkCount()).isEqualTo(2);
Assertions.assertThat(cache.hitCount()).isEqualTo(1); assertThat(cache.hitCount()).isEqualTo(1);
} }
@Test public void responseCachedWithoutConsumingFullBody() throws IOException { @Test public void responseCachedWithoutConsumingFullBody() throws IOException {
@ -704,14 +706,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.body().source().readUtf8(2)).isEqualTo("AB"); assertThat(response1.body().source().readUtf8(2)).isEqualTo("AB");
response1.body().close(); response1.body().close();
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD"); assertThat(response2.body().source().readUtf8()).isEqualTo("ABCD");
response2.body().close(); response2.body().close();
} }
@ -732,10 +734,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo(""); assertThat(response.body().string()).isEqualTo("");
RecordedRequest request = server.takeRequest(); 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 { @Test public void receiveResponseCookies() throws Exception {
@ -751,7 +753,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo(""); assertThat(response.body().string()).isEqualTo("");
cookieJar.assertResponseCookies("a=b; path=/"); cookieJar.assertResponseCookies("a=b; path=/");
} }
@ -770,13 +772,13 @@ public final class HttpOverHttp2Test {
call1.cancel(); call1.cancel();
// That connection is pooled, and it works. // 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() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("def"); assertThat(response2.body().string()).isEqualTo("def");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Clean up the connection. // Clean up the connection.
response.close(); response.close();
@ -793,12 +795,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("abc"); assertThat(response.body().string()).isEqualTo("abc");
// New connection. // New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reused connection. // Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception { @Test public void recoverFromOneInternalErrorRequiresNewConnection() throws Exception {
@ -816,12 +818,12 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("abc"); assertThat(response.body().string()).isEqualTo("abc");
// New connection. // New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// New connection. // New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception { @Test public void recoverFromMultipleRefusedStreamsRequiresNewConnection() throws Exception {
@ -842,14 +844,14 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("abc"); assertThat(response.body().string()).isEqualTo("abc");
// New connection. // New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reused connection. // Reused connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
// New connection. // New connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void recoverFromCancelReusesConnection() throws Exception { @Test public void recoverFromCancelReusesConnection() throws Exception {
@ -870,8 +872,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("def"); assertThat(response.body().string()).isEqualTo("def");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
} }
@Test public void recoverFromMultipleCancelReusesConnection() throws Exception { @Test public void recoverFromMultipleCancelReusesConnection() throws Exception {
@ -896,8 +898,8 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ghi"); assertThat(response.body().string()).isEqualTo("ghi");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
} }
/** Make a call and canceling it as soon as it's accepted by the server. */ /** Make a call and canceling it as soon as it's accepted by the server. */
@ -915,7 +917,7 @@ public final class HttpOverHttp2Test {
fail(); fail();
} }
}); });
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo( assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(
(long) expectedSequenceNumber); (long) expectedSequenceNumber);
call.cancel(); call.cancel();
latch.await(); latch.await();
@ -947,7 +949,7 @@ public final class HttpOverHttp2Test {
call.execute(); call.execute();
fail(); fail();
} catch (StreamResetException expected) { } catch (StreamResetException expected) {
Assertions.assertThat(expected.errorCode).isEqualTo(errorCode); assertThat(expected.errorCode).isEqualTo(errorCode);
} }
} }
@ -997,24 +999,24 @@ public final class HttpOverHttp2Test {
.build(); .build();
blockingAuthClient.newCall(request).enqueue(callback); blockingAuthClient.newCall(request).enqueue(callback);
String response1 = responses.take(); String response1 = responses.take();
Assertions.assertThat(response1).isEqualTo(""); assertThat(response1).isEqualTo("");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Now make the second request which will restrict the first HTTP/2 connection from creating new // Now make the second request which will restrict the first HTTP/2 connection from creating new
// streams. // streams.
client.newCall(request).enqueue(callback); client.newCall(request).enqueue(callback);
String response2 = responses.take(); String response2 = responses.take();
Assertions.assertThat(response2).isEqualTo("DEF"); assertThat(response2).isEqualTo("DEF");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Let the first request proceed. It should discard the the held HTTP/2 connection and get a new // Let the first request proceed. It should discard the the held HTTP/2 connection and get a new
// one. // one.
latch.countDown(); latch.countDown();
String response3 = responses.take(); String response3 = responses.take();
Assertions.assertThat(response3).isEqualTo("ABC"); assertThat(response3).isEqualTo("ABC");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
} }
@Test public void nonAsciiResponseHeader() throws Exception { @Test public void nonAsciiResponseHeader() throws Exception {
@ -1028,8 +1030,8 @@ public final class HttpOverHttp2Test {
Response response = call.execute(); Response response = call.execute();
response.close(); response.close();
Assertions.assertThat(response.header("Alpha")).isEqualTo("α"); assertThat(response.header("Alpha")).isEqualTo("α");
Assertions.assertThat(response.header("β")).isEqualTo("Beta"); assertThat(response.header("β")).isEqualTo("Beta");
} }
@Test public void serverSendsPushPromise_GET() throws Exception { @Test public void serverSendsPushPromise_GET() throws Exception {
@ -1045,20 +1047,20 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo(""); assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo( assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort())); (server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest(); RecordedRequest pushedRequest = server.takeRequest();
Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo( assertThat(pushedRequest.getRequestLine()).isEqualTo(
"GET /foo/bar HTTP/1.1"); "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 { @Test public void serverSendsPushPromise_HEAD() throws Exception {
@ -1073,20 +1075,20 @@ public final class HttpOverHttp2Test {
.url(server.url("/foo")) .url(server.url("/foo"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABCDE"); assertThat(response.body().string()).isEqualTo("ABCDE");
Assertions.assertThat(response.code()).isEqualTo(200); assertThat(response.code()).isEqualTo(200);
Assertions.assertThat(response.message()).isEqualTo(""); assertThat(response.message()).isEqualTo("");
RecordedRequest request = server.takeRequest(); RecordedRequest request = server.takeRequest();
Assertions.assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1"); assertThat(request.getRequestLine()).isEqualTo("GET /foo HTTP/1.1");
Assertions.assertThat(request.getHeader(":scheme")).isEqualTo(scheme); assertThat(request.getHeader(":scheme")).isEqualTo(scheme);
Assertions.assertThat(request.getHeader(":authority")).isEqualTo( assertThat(request.getHeader(":authority")).isEqualTo(
(server.getHostName() + ":" + server.getPort())); (server.getHostName() + ":" + server.getPort()));
RecordedRequest pushedRequest = server.takeRequest(); RecordedRequest pushedRequest = server.takeRequest();
Assertions.assertThat(pushedRequest.getRequestLine()).isEqualTo( assertThat(pushedRequest.getRequestLine()).isEqualTo(
"HEAD /foo/bar HTTP/1.1"); "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 { @Test public void noDataFramesSentWithNullRequestBody() throws Exception {
@ -1098,13 +1100,15 @@ public final class HttpOverHttp2Test {
.method("DELETE", null) .method("DELETE", null)
.build()); .build());
Response response = call.execute(); 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<String> logs = http2Handler.takeAll(); List<String> 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 { @Test public void emptyDataFrameSentWithEmptyBody() throws Exception {
@ -1116,14 +1120,18 @@ public final class HttpOverHttp2Test {
.method("DELETE", Util.EMPTY_REQUEST) .method("DELETE", Util.EMPTY_REQUEST)
.build()); .build());
Response response = call.execute(); 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<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
assertThat("header logged", firstFrame(logs, "HEADERS"), containsString("HEADERS END_HEADERS")); assertThat(firstFrame(logs, "HEADERS"))
assertThat("data logged", firstFrame(logs, "DATA"), containsString("0 DATA END_STREAM")); .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 { @Test public void pingsTransmitted() throws Exception {
@ -1141,19 +1149,19 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); 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. // Confirm a single ping was sent and received, and its reply was sent and received.
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
(long) 1); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo( assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ")).isEqualTo(
(long) 1); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")).isEqualTo( assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ACK")).isEqualTo(
(long) 1); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo(
(long) 1); (long) 1);
} }
@ -1177,19 +1185,19 @@ public final class HttpOverHttp2Test {
call.execute(); call.execute();
fail(); fail();
} catch (StreamResetException expected) { } catch (StreamResetException expected) {
Assertions.assertThat(expected.getMessage()).isEqualTo( assertThat(expected.getMessage()).isEqualTo(
"stream was reset: PROTOCOL_ERROR"); "stream was reset: PROTOCOL_ERROR");
} }
long elapsedUntilFailure = System.nanoTime() - executeAtNanos; long elapsedUntilFailure = System.nanoTime() - executeAtNanos;
Assertions.assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo( assertThat((double) TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure)).isCloseTo(
(double) 1000, offset(250d)); (double) 1000, offset(250d));
// Confirm a single ping was sent but not acknowledged. // Confirm a single ping was sent but not acknowledged.
List<String> logs = http2Handler.takeAll(); List<String> logs = http2Handler.takeAll();
Assertions.assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo( assertThat(countFrames(logs, "FINE: >> 0x00000000 8 PING ")).isEqualTo(
(long) 1); (long) 1);
Assertions.assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo( assertThat(countFrames(logs, "FINE: << 0x00000000 8 PING ACK")).isEqualTo(
(long) 0); (long) 0);
} }
@ -1227,7 +1235,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo(""); assertThat(response.body().string()).isEqualTo("");
server.enqueue(new MockResponse() server.enqueue(new MockResponse()
.setBody("ABC")); .setBody("ABC"));
@ -1251,17 +1259,17 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response3 = call3.execute(); Response response3 = call3.execute();
Assertions.assertThat(response1.body().string()).isEqualTo("ABC"); assertThat(response1.body().string()).isEqualTo("ABC");
Assertions.assertThat(response2.body().string()).isEqualTo("DEF"); assertThat(response2.body().string()).isEqualTo("DEF");
Assertions.assertThat(response3.body().string()).isEqualTo("GHI"); assertThat(response3.body().string()).isEqualTo("GHI");
// Settings connection. // Settings connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
// Reuse settings connection. // Reuse settings connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(1);
// Reuse settings connection. // Reuse settings connection.
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(2);
// New connection! // New connection!
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void connectionNotReusedAfterShutdown() throws Exception { @Test public void connectionNotReusedAfterShutdown() throws Exception {
@ -1275,15 +1283,15 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response1 = call1.execute(); Response response1 = call1.execute();
Assertions.assertThat(response1.body().string()).isEqualTo("ABC"); assertThat(response1.body().string()).isEqualTo("ABC");
Call call2 = client.newCall(new Request.Builder() Call call2 = client.newCall(new Request.Builder()
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("DEF"); assertThat(response2.body().string()).isEqualTo("DEF");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
/** /**
@ -1310,7 +1318,7 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("ABC"); assertThat(response.body().string()).isEqualTo("ABC");
// Wait until the GOAWAY has been processed. // Wait until the GOAWAY has been processed.
RealConnection connection = (RealConnection) chain.connection(); RealConnection connection = (RealConnection) chain.connection();
while (connection.isHealthy(false)) ; while (connection.isHealthy(false)) ;
@ -1324,10 +1332,10 @@ public final class HttpOverHttp2Test {
.url(server.url("/")) .url(server.url("/"))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("DEF"); assertThat(response.body().string()).isEqualTo("DEF");
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
Assertions.assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0); assertThat(server.takeRequest().getSequenceNumber()).isEqualTo(0);
} }
@Test public void responseHeadersAfterGoaway() throws Exception { @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);
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"); assertThat(bodies.poll(2, SECONDS)).isEqualTo("DEF");
Assertions.assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC"); assertThat(bodies.poll(2, SECONDS)).isEqualTo("ABC");
Assertions.assertThat(server.getRequestCount()).isEqualTo(2); assertThat(server.getRequestCount()).isEqualTo(2);
} }
/** /**
@ -1394,7 +1402,7 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call2") .url("https://android.com/call2")
.build()); .build());
Response response2 = call2.execute(); Response response2 = call2.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("call2 response"); assertThat(response2.body().string()).isEqualTo("call2 response");
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -1420,27 +1428,27 @@ public final class HttpOverHttp2Test {
.url("https://android.com/call1") .url("https://android.com/call1")
.build()); .build());
Response response2 = call1.execute(); Response response2 = call1.execute();
Assertions.assertThat(response2.body().string()).isEqualTo("call1 response"); assertThat(response2.body().string()).isEqualTo("call1 response");
RecordedRequest call1Connect = server.takeRequest(); RecordedRequest call1Connect = server.takeRequest();
Assertions.assertThat(call1Connect.getMethod()).isEqualTo("CONNECT"); assertThat(call1Connect.getMethod()).isEqualTo("CONNECT");
Assertions.assertThat(call1Connect.getSequenceNumber()).isEqualTo(0); assertThat(call1Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Connect = server.takeRequest(); RecordedRequest call2Connect = server.takeRequest();
Assertions.assertThat(call2Connect.getMethod()).isEqualTo("CONNECT"); assertThat(call2Connect.getMethod()).isEqualTo("CONNECT");
Assertions.assertThat(call2Connect.getSequenceNumber()).isEqualTo(0); assertThat(call2Connect.getSequenceNumber()).isEqualTo(0);
RecordedRequest call2Get = server.takeRequest(); RecordedRequest call2Get = server.takeRequest();
Assertions.assertThat(call2Get.getMethod()).isEqualTo("GET"); assertThat(call2Get.getMethod()).isEqualTo("GET");
Assertions.assertThat(call2Get.getPath()).isEqualTo("/call2"); assertThat(call2Get.getPath()).isEqualTo("/call2");
Assertions.assertThat(call2Get.getSequenceNumber()).isEqualTo(0); assertThat(call2Get.getSequenceNumber()).isEqualTo(0);
RecordedRequest call1Get = server.takeRequest(); RecordedRequest call1Get = server.takeRequest();
Assertions.assertThat(call1Get.getMethod()).isEqualTo("GET"); assertThat(call1Get.getMethod()).isEqualTo("GET");
Assertions.assertThat(call1Get.getPath()).isEqualTo("/call1"); assertThat(call1Get.getPath()).isEqualTo("/call1");
Assertions.assertThat(call1Get.getSequenceNumber()).isEqualTo(1); 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 */ /** https://github.com/square/okhttp/issues/3103 */
@ -1463,10 +1471,10 @@ public final class HttpOverHttp2Test {
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo(""); assertThat(response.body().string()).isEqualTo("");
RecordedRequest recordedRequest = server.takeRequest(); RecordedRequest recordedRequest = server.takeRequest();
Assertions.assertThat(recordedRequest.getHeader(":authority")).isEqualTo( assertThat(recordedRequest.getHeader(":authority")).isEqualTo(
"privateobject.com"); "privateobject.com");
} }
@ -1493,7 +1501,7 @@ public final class HttpOverHttp2Test {
.url(server.url(path)) .url(server.url(path))
.build()); .build());
Response response = call.execute(); Response response = call.execute();
Assertions.assertThat(response.body().string()).isEqualTo("A"); assertThat(response.body().string()).isEqualTo("A");
countDownLatch.countDown(); countDownLatch.countDown();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -42,6 +42,7 @@ import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion; import static okhttp3.internal.platform.PlatformTest.getJvmSpecVersion;
import static okhttp3.internal.platform.PlatformTest.getPlatform; import static okhttp3.internal.platform.PlatformTest.getPlatform;
@ -281,7 +282,7 @@ public final class ClientAuthTest {
X509KeyManager keyManager = newKeyManager( X509KeyManager keyManager = newKeyManager(
null, serverCert, serverIntermediateCa.certificate()); null, serverCert, serverIntermediateCa.certificate());
X509TrustManager trustManager = newTrustManager( X509TrustManager trustManager = newTrustManager(
null, Arrays.asList(serverRootCa.certificate(), clientRootCa.certificate())); null, asList(serverRootCa.certificate(), clientRootCa.certificate()));
SSLContext sslContext = SSLContext.getInstance("TLS"); SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager},
new SecureRandom()); new SecureRandom());

View File

@ -21,8 +21,6 @@ import java.io.InterruptedIOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random; import java.util.Random;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -50,6 +48,7 @@ import org.junit.Ignore;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static okhttp3.TestUtil.defaultClient; import static okhttp3.TestUtil.defaultClient;
import static okhttp3.TestUtil.ensureAllConnectionsReleased; import static okhttp3.TestUtil.ensureAllConnectionsReleased;
import static okhttp3.TestUtil.repeat; import static okhttp3.TestUtil.repeat;
@ -416,16 +415,16 @@ public final class WebSocketHttpTest {
// Send messages until the client's outgoing buffer overflows! // Send messages until the client's outgoing buffer overflows!
ByteString message = ByteString.of(new byte[1024 * 1024]); ByteString message = ByteString.of(new byte[1024 * 1024]);
int messageCount = 0; long messageCount = 0;
while (true) { while (true) {
boolean success = webSocket.send(message); boolean success = webSocket.send(message);
if (!success) break; if (!success) break;
messageCount++; messageCount++;
long queueSize = webSocket.queueSize(); 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. // 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. // 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 { @Test public void webSocketConnectionIsReleased() throws Exception {
// This test assumes HTTP/1.1 pooling semantics. // This test assumes HTTP/1.1 pooling semantics.
client = client.newBuilder() client = client.newBuilder()
.protocols(Arrays.asList(Protocol.HTTP_1_1)) .protocols(asList(Protocol.HTTP_1_1))
.build(); .build();
webServer.enqueue(new MockResponse() webServer.enqueue(new MockResponse()

View File

@ -19,7 +19,6 @@ import java.io.EOFException;
import java.io.IOException; import java.io.IOException;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.util.Random; import java.util.Random;
import java.util.regex.Pattern;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import okio.Buffer; import okio.Buffer;
import okio.ByteString; import okio.ByteString;
@ -309,9 +308,7 @@ public final class WebSocketReaderTest {
clientReader.processNextFrame(); clientReader.processNextFrame();
fail(); fail();
} catch (ProtocolException e) { } catch (ProtocolException e) {
String message = e.getMessage(); assertThat(e.getMessage()).matches("Code \\d+ is reserved and may not be used.");
assertThat(Pattern.matches("Code \\d+ is reserved and may not be used.", message)).overridingErrorMessage(
message).isTrue();
} }
} }
assertThat(count).isEqualTo(1991); assertThat(count).isEqualTo(1991);

View File

@ -16,7 +16,6 @@
package okhttp3.internal.ws; package okhttp3.internal.ws;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@ -161,7 +160,7 @@ public final class WebSocketRecorder extends WebSocketListener {
} }
public void assertExhausted() { public void assertExhausted() {
assertThat(events.isEmpty()).overridingErrorMessage("Remaining events: " + events).isTrue(); assertThat(events).isEmpty();
} }
public WebSocket assertOpen() { public WebSocket assertOpen() {
@ -191,8 +190,7 @@ public final class WebSocketRecorder extends WebSocketListener {
assertThat(failure.response).isNull(); assertThat(failure.response).isNull();
assertThat(failure.t.getClass()).isEqualTo(cls); assertThat(failure.t.getClass()).isEqualTo(cls);
if (messages.length > 0) { if (messages.length > 0) {
assertThat(Arrays.asList(messages).contains(failure.t.getMessage())).overridingErrorMessage( assertThat(messages).contains(failure.t.getMessage());
failure.t.getMessage()).isTrue();
} }
} }

View File

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

View File

@ -23,14 +23,12 @@ import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import okio.ByteString; import okio.ByteString;
import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralName;
import org.junit.Test; import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset; import static org.assertj.core.data.Offset.offset;
@ -42,7 +40,7 @@ public final class HeldCertificateTest {
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
assertThat(certificate.getSubjectX500Principal().getName()).overridingErrorMessage( assertThat(certificate.getSubjectX500Principal().getName()).overridingErrorMessage(
"self-signed").isEqualTo(certificate.getIssuerX500Principal().getName()); "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.getSerialNumber()).isEqualTo(BigInteger.ONE);
assertThat(certificate.getSubjectAlternativeNames()).isNull(); assertThat(certificate.getSubjectAlternativeNames()).isNull();
@ -87,11 +85,9 @@ public final class HeldCertificateTest {
.build(); .build();
X509Certificate certificate = heldCertificate.certificate(); X509Certificate certificate = heldCertificate.certificate();
List<List<?>> subjectAlternativeNames = new ArrayList<>( assertThat(certificate.getSubjectAlternativeNames()).containsExactly(
certificate.getSubjectAlternativeNames()); asList(GeneralName.iPAddress, "1.1.1.1"),
assertThat(Arrays.asList( asList(GeneralName.dNSName, "cash.app"));
Arrays.asList(GeneralName.iPAddress, "1.1.1.1"),
Arrays.asList(GeneralName.dNSName, "cash.app"))).isEqualTo(subjectAlternativeNames);
} }
@Test public void commonName() { @Test public void commonName() {

View File

@ -18,7 +18,6 @@ package okhttp3;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
@ -29,6 +28,8 @@ import javax.net.ssl.SSLPeerUnverifiedException;
import okhttp3.internal.tls.CertificateChainCleaner; import okhttp3.internal.tls.CertificateChainCleaner;
import okio.ByteString; import okio.ByteString;
import static java.util.Arrays.asList;
/** /**
* Constrains which certificates are trusted. Pinning certificates defends against attacks on * Constrains which certificates are trusted. Pinning certificates defends against attacks on
* certificate authorities. It also prevents connections through man-in-the-middle certificate * 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)}. */ /** @deprecated replaced with {@link #check(String, List)}. */
public void check(String hostname, Certificate... peerCertificates) public void check(String hostname, Certificate... peerCertificates)
throws SSLPeerUnverifiedException { throws SSLPeerUnverifiedException {
check(hostname, Arrays.asList(peerCertificates)); check(hostname, asList(peerCertificates));
} }
/** /**

View File

@ -17,9 +17,10 @@ package okhttp3;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List; 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 * 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 * {@linkplain #SYSTEM system DNS service}, which is the default. Some applications may provide
@ -36,7 +37,7 @@ public interface Dns {
Dns SYSTEM = hostname -> { Dns SYSTEM = hostname -> {
if (hostname == null) throw new UnknownHostException("hostname == null"); if (hostname == null) throw new UnknownHostException("hostname == null");
try { try {
return Arrays.asList(InetAddress.getAllByName(hostname)); return asList(InetAddress.getAllByName(hostname));
} catch (NullPointerException e) { } catch (NullPointerException e) {
UnknownHostException unknownHostException = UnknownHostException unknownHostException =
new UnknownHostException("Broken system behaviour for dns lookup of " + hostname); new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);

View File

@ -59,6 +59,7 @@ import okio.Source;
import static java.nio.charset.StandardCharsets.UTF_16BE; import static java.nio.charset.StandardCharsets.UTF_16BE;
import static java.nio.charset.StandardCharsets.UTF_16LE; import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
/** Junk drawer of utility methods. */ /** Junk drawer of utility methods. */
public final class Util { public final class Util {
@ -231,7 +232,7 @@ public final class Util {
/** Returns an immutable list containing {@code elements}. */ /** Returns an immutable list containing {@code elements}. */
@SafeVarargs @SafeVarargs
public static <T> List<T> immutableList(T... elements) { public static <T> List<T> immutableList(T... elements) {
return Collections.unmodifiableList(Arrays.asList(elements.clone())); return Collections.unmodifiableList(asList(elements.clone()));
} }
public static ThreadFactory threadFactory(String name, boolean daemon) { public static ThreadFactory threadFactory(String name, boolean daemon) {

View File

@ -37,6 +37,8 @@ import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
import static java.util.Arrays.asList;
public final class CustomCipherSuites { public final class CustomCipherSuites {
private final OkHttpClient client; 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 // 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 // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should
// not customize the cipher suites list. // not customize the cipher suites list.
List<CipherSuite> customCipherSuites = Arrays.asList( List<CipherSuite> customCipherSuites = asList(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,