From 8f5e344aba7b734efa61977651838a88d288a187 Mon Sep 17 00:00:00 2001 From: Jake Wharton Date: Fri, 24 Jul 2015 12:08:21 -0400 Subject: [PATCH] Fold MockWebServerRule into MockWebServer. This avoid needing to duplicate the methods on the rule which historically was a subset of everything. JUnit is now a required dependency. --- mockwebserver/pom.xml | 1 - .../okhttp/mockwebserver/MockWebServer.java | 82 ++++++------ .../mockwebserver/rule/MockWebServerRule.java | 93 -------------- .../mockwebserver/MockWebServerTest.java | 71 ++++++++--- .../rule/MockWebServerRuleTest.java | 84 ------------- .../okhttp/android/HttpResponseCacheTest.java | 5 +- .../internal/huc/JavaApiConverterTest.java | 4 +- .../internal/huc/ResponseCacheTest.java | 9 +- .../java/com/squareup/okhttp/CacheTest.java | 9 +- .../java/com/squareup/okhttp/CallTest.java | 42 +++---- .../com/squareup/okhttp/InterceptorTest.java | 8 +- .../internal/http/HttpOverSpdyTest.java | 8 +- .../internal/http/URLConnectionTest.java | 117 +++++++++--------- .../com/squareup/okhttp/OkUrlFactoryTest.java | 6 +- .../okhttp/UrlConnectionCacheTest.java | 9 +- .../squareup/okhttp/ws/WebSocketCallTest.java | 8 +- 16 files changed, 201 insertions(+), 355 deletions(-) delete mode 100644 mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRule.java delete mode 100644 mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRuleTest.java diff --git a/mockwebserver/pom.xml b/mockwebserver/pom.xml index a2f5b2cce5e0..3d5c842f8ad6 100644 --- a/mockwebserver/pom.xml +++ b/mockwebserver/pom.xml @@ -36,7 +36,6 @@ junit junit - true diff --git a/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/MockWebServer.java b/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/MockWebServer.java index 8d87f06d660d..458c6f9a5c6e 100644 --- a/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/MockWebServer.java +++ b/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/MockWebServer.java @@ -37,7 +37,6 @@ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.Proxy; import java.net.ServerSocket; @@ -78,6 +77,9 @@ import okio.Okio; import okio.Sink; import okio.Timeout; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; import static com.squareup.okhttp.mockwebserver.SocketPolicy.DISCONNECT_AT_START; import static com.squareup.okhttp.mockwebserver.SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY; @@ -88,7 +90,7 @@ * A scriptable web server. Callers supply canned responses and the server * replays them upon request in sequence. */ -public final class MockWebServer { +public final class MockWebServer implements TestRule { private static final X509TrustManager UNTRUSTED_TRUST_MANAGER = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { @@ -127,44 +129,61 @@ public final class MockWebServer { private List protocols = Util.immutableList(Protocol.HTTP_2, Protocol.SPDY_3, Protocol.HTTP_1_1); - public void setServerSocketFactory(ServerSocketFactory serverSocketFactory) { - if (serverSocketFactory == null) throw new IllegalArgumentException("null serverSocketFactory"); - this.serverSocketFactory = serverSocketFactory; + private boolean started; + + private synchronized void maybeStart() { + if (started) return; + try { + start(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override public void evaluate() throws Throwable { + maybeStart(); + try { + base.evaluate(); + } finally { + try { + shutdown(); + } catch (IOException e) { + logger.log(Level.WARNING, "MockWebServer shutdown failed", e); + } + } + } + }; } public int getPort() { - if (port == -1) throw new IllegalStateException("Call start() before getPort()"); + maybeStart(); return port; } public String getHostName() { - if (inetSocketAddress == null) { - throw new IllegalStateException("Call start() before getHostName()"); - } + maybeStart(); return inetSocketAddress.getHostName(); } public Proxy toProxyAddress() { - if (inetSocketAddress == null) { - throw new IllegalStateException("Call start() before toProxyAddress()"); - } + maybeStart(); InetSocketAddress address = new InetSocketAddress(inetSocketAddress.getAddress(), getPort()); return new Proxy(Proxy.Type.HTTP, address); } + public void setServerSocketFactory(ServerSocketFactory serverSocketFactory) { + this.serverSocketFactory = serverSocketFactory; + } + /** * Returns a URL for connecting to this server. * @param path the request path, such as "/". */ @Deprecated public URL getUrl(String path) { - try { - return sslSocketFactory != null - ? new URL("https://" + getHostName() + ":" + getPort() + path) - : new URL("http://" + getHostName() + ":" + getPort() + path); - } catch (MalformedURLException e) { - throw new AssertionError(e); - } + return url(path).url(); } /** @@ -177,8 +196,8 @@ public HttpUrl url(String path) { .scheme(sslSocketFactory != null ? "https" : "http") .host(getHostName()) .port(getPort()) - .encodedPath(path) - .build(); + .build() + .resolve(path); } /** @@ -284,16 +303,6 @@ public void enqueue(MockResponse response) { ((QueueDispatcher) dispatcher).enqueueResponse(response.clone()); } - /** @deprecated Use {@link #start()}. */ - public void play() throws IOException { - start(); - } - - /** @deprecated Use {@link #start(int)}. */ - public void play(int port) throws IOException { - start(port); - } - /** Equivalent to {@code start(0)}. */ public void start() throws IOException { start(0); @@ -328,8 +337,10 @@ public void start(InetAddress inetAddress, int port) throws IOException { * * @param inetSocketAddress the socket address to bind the server on */ - private void start(InetSocketAddress inetSocketAddress) throws IOException { - if (executor != null) throw new IllegalStateException("start() already called"); + private synchronized void start(InetSocketAddress inetSocketAddress) throws IOException { + if (started) throw new IllegalStateException("start() already called"); + started = true; + executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false)); this.inetSocketAddress = inetSocketAddress; serverSocket = serverSocketFactory.createServerSocket(); @@ -382,7 +393,8 @@ private void acceptConnections() throws Exception { }); } - public void shutdown() throws IOException { + public synchronized void shutdown() throws IOException { + if (!started) return; if (serverSocket == null) throw new IllegalStateException("shutdown() before start()"); // Cause acceptConnections() to break out. @@ -927,7 +939,7 @@ private void pushPromises(FramedStream stream, List promises) throw List
pushedHeaders = new ArrayList<>(); pushedHeaders.add(new Header(stream.getConnection().getProtocol() == Protocol.SPDY_3 ? Header.TARGET_HOST - : Header.TARGET_AUTHORITY, getUrl(pushPromise.getPath()).getHost())); + : Header.TARGET_AUTHORITY, url(pushPromise.getPath()).host())); pushedHeaders.add(new Header(Header.TARGET_METHOD, pushPromise.getMethod())); pushedHeaders.add(new Header(Header.TARGET_PATH, pushPromise.getPath())); Headers pushPromiseHeaders = pushPromise.getHeaders(); diff --git a/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRule.java b/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRule.java deleted file mode 100644 index d452344a7450..000000000000 --- a/mockwebserver/src/main/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRule.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2014 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.squareup.okhttp.mockwebserver.rule; - -import com.squareup.okhttp.HttpUrl; -import com.squareup.okhttp.mockwebserver.MockResponse; -import com.squareup.okhttp.mockwebserver.MockWebServer; -import com.squareup.okhttp.mockwebserver.RecordedRequest; -import java.io.IOException; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.junit.rules.ExternalResource; - -/** - * Allows you to use {@link MockWebServer} as a JUnit test rule. - * - *

This rule starts {@link MockWebServer} on an available port before your test runs, and shuts - * it down after it completes. - */ -public class MockWebServerRule extends ExternalResource { - private static final Logger logger = Logger.getLogger(MockWebServerRule.class.getName()); - - private final MockWebServer server = new MockWebServer(); - private boolean started; - - @Override protected void before() { - if (started) return; - started = true; - try { - server.start(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override protected void after() { - try { - server.shutdown(); - } catch (IOException e) { - logger.log(Level.WARNING, "MockWebServer shutdown failed", e); - } - } - - public String getHostName() { - if (!started) before(); - return server.getHostName(); - } - - public int getPort() { - if (!started) before(); - return server.getPort(); - } - - public int getRequestCount() { - return server.getRequestCount(); - } - - public void enqueue(MockResponse response) { - server.enqueue(response); - } - - public RecordedRequest takeRequest() throws InterruptedException { - return server.takeRequest(); - } - - @Deprecated - public URL getUrl(String path) { - return server.getUrl(path); - } - - public HttpUrl url(String path) { - return server.url(path); - } - - /** For any other functionality, use the {@linkplain MockWebServer} directly. */ - public MockWebServer get() { - return server; - } -} diff --git a/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/MockWebServerTest.java b/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/MockWebServerTest.java index a059e5921e7f..e729393893fc 100644 --- a/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/MockWebServerTest.java +++ b/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/MockWebServerTest.java @@ -16,11 +16,11 @@ package com.squareup.okhttp.mockwebserver; import com.squareup.okhttp.Headers; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; @@ -29,17 +29,23 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.After; import org.junit.Rule; import org.junit.Test; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public final class MockWebServerTest { - @Rule public final MockWebServerRule server = new MockWebServerRule(); + @Rule public final MockWebServer server = new MockWebServer(); @Test public void defaultMockResponse() { MockResponse response = new MockResponse(); @@ -230,9 +236,7 @@ public final class MockWebServerTest { assertTrue(String.format("Request + Response: %sms", elapsedMillis), elapsedMillis < 1000); } - /** - * Delay the response body by sleeping 1s. - */ + /** Delay the response body by sleeping 1s. */ @Test public void delayResponse() throws IOException { server.enqueue(new MockResponse() .setBody("ABCDEF") @@ -242,17 +246,11 @@ public final class MockWebServerTest { URLConnection connection = server.getUrl("/").openConnection(); InputStream in = connection.getInputStream(); assertEquals('A', in.read()); - assertEquals('B', in.read()); - assertEquals('C', in.read()); - assertEquals('D', in.read()); - assertEquals('E', in.read()); - assertEquals('F', in.read()); - assertEquals(-1, in.read()); long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = NANOSECONDS.toMillis(elapsedNanos); - assertTrue(String.format("Request + Response: %sms", elapsedMillis), elapsedMillis >= 1000); - assertTrue(String.format("Request + Response: %sms", elapsedMillis), elapsedMillis <= 1100); + + in.close(); } @Test public void disconnectHalfway() throws IOException { @@ -279,11 +277,7 @@ private List headersToList(MockResponse response) { @Test public void shutdownWithoutStart() throws IOException { MockWebServer server = new MockWebServer(); - try { - server.shutdown(); - fail(); - } catch (IllegalStateException expected) { - } + server.shutdown(); } @Test public void shutdownWithoutEnqueue() throws IOException { @@ -291,4 +285,45 @@ private List headersToList(MockResponse response) { server.start(); server.shutdown(); } + + @After public void tearDown() throws IOException { + server.shutdown(); + } + + @Test public void portImplicitlyStarts() throws IOException { + assertTrue(server.getPort() > 0); + } + + @Test public void hostNameImplicitlyStarts() throws IOException { + assertNotNull(server.getHostName()); + } + + @Test public void toProxyAddressImplicitlyStarts() throws IOException { + assertNotNull(server.toProxyAddress()); + } + + @Test public void differentInstancesGetDifferentPorts() throws IOException { + MockWebServer other = new MockWebServer(); + assertNotEquals(server.getPort(), other.getPort()); + other.shutdown(); + } + + @Test public void statementStartsAndStops() throws Throwable { + final AtomicBoolean called = new AtomicBoolean(); + Statement statement = server.apply(new Statement() { + @Override public void evaluate() throws Throwable { + called.set(true); + server.getUrl("/").openConnection().connect(); + } + }, Description.EMPTY); + + statement.evaluate(); + + assertTrue(called.get()); + try { + server.getUrl("/").openConnection().connect(); + fail(); + } catch (ConnectException expected) { + } + } } diff --git a/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRuleTest.java b/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRuleTest.java deleted file mode 100644 index 43ceebc6bbd1..000000000000 --- a/mockwebserver/src/test/java/com/squareup/okhttp/mockwebserver/rule/MockWebServerRuleTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2014 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.squareup.okhttp.mockwebserver.rule; - -import com.squareup.okhttp.mockwebserver.MockResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.ConnectException; -import java.net.HttpURLConnection; -import java.net.URL; -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class MockWebServerRuleTest { - - private MockWebServerRule server = new MockWebServerRule(); - - @After public void tearDown() { - server.after(); - } - - @Test public void whenRuleCreatedPortIsAvailable() throws IOException { - assertTrue(server.getPort() > 0); - } - - @Test public void differentRulesGetDifferentPorts() throws IOException { - assertNotEquals(server.getPort(), new MockWebServerRule().getPort()); - } - - @Test public void beforePlaysServer() throws Exception { - server.before(); - assertEquals(server.getPort(), server.get().getPort()); - server.getUrl("/").openConnection().connect(); - } - - @Test public void afterStopsServer() throws Exception { - server.before(); - server.after(); - - try { - server.getUrl("/").openConnection().connect(); - fail(); - } catch (ConnectException e) { - } - } - - @Test public void typicalUsage() throws Exception { - server.before(); // Implicitly called when @Rule. - - server.enqueue(new MockResponse().setBody("hello world")); - - URL url = server.getUrl("/aaa"); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - InputStream in = connection.getInputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - assertEquals("hello world", reader.readLine()); - - assertEquals(1, server.getRequestCount()); - assertEquals("GET /aaa HTTP/1.1", server.takeRequest().getRequestLine()); - - server.after(); // Implicitly called when @Rule. - } -} - diff --git a/okhttp-android-support/src/test/java/com/squareup/okhttp/android/HttpResponseCacheTest.java b/okhttp-android-support/src/test/java/com/squareup/okhttp/android/HttpResponseCacheTest.java index c34979045305..0d6278482658 100644 --- a/okhttp-android-support/src/test/java/com/squareup/okhttp/android/HttpResponseCacheTest.java +++ b/okhttp-android-support/src/test/java/com/squareup/okhttp/android/HttpResponseCacheTest.java @@ -21,7 +21,6 @@ import com.squareup.okhttp.OkUrlFactory; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import org.junit.After; import org.junit.Before; @@ -53,14 +52,12 @@ public final class HttpResponseCacheTest { @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); - @Rule public MockWebServerRule serverRule = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); private File cacheDir; - private MockWebServer server; private OkUrlFactory client; @Before public void setUp() throws Exception { - server = serverRule.get(); cacheDir = cacheRule.getRoot(); client = new OkUrlFactory(new OkHttpClient()); } diff --git a/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java b/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java index 227765abb8b9..449f3c9ffe61 100644 --- a/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java +++ b/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java @@ -25,7 +25,7 @@ import com.squareup.okhttp.ResponseBody; import com.squareup.okhttp.internal.Internal; import com.squareup.okhttp.internal.Util; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; +import com.squareup.okhttp.mockwebserver.MockWebServer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -93,7 +93,7 @@ public class JavaApiConverterTest { + "fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n" + "-----END CERTIFICATE-----"); - @Rule public MockWebServerRule server = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); @Before public void setUp() throws Exception { Internal.initializeInstanceForTests(); diff --git a/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/ResponseCacheTest.java b/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/ResponseCacheTest.java index 83d1f64ce726..ae9153da6e7e 100644 --- a/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/ResponseCacheTest.java +++ b/okhttp-android-support/src/test/java/com/squareup/okhttp/internal/huc/ResponseCacheTest.java @@ -27,7 +27,6 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; @@ -100,19 +99,15 @@ public final class ResponseCacheTest { private static final SSLContext sslContext = SslContextBuilder.localhost(); @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); - @Rule public MockWebServerRule serverRule = new MockWebServerRule(); - @Rule public MockWebServerRule server2Rule = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); + @Rule public MockWebServer server2 = new MockWebServer(); private OkHttpClient client; - private MockWebServer server; - private MockWebServer server2; private ResponseCache cache; private CookieManager cookieManager; @Before public void setUp() throws Exception { - server = serverRule.get(); server.setProtocolNegotiationEnabled(false); - server2 = server2Rule.get(); client = new OkHttpClient(); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java index 7d5f0e8507e3..c9b6bcb3f37f 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java @@ -22,7 +22,6 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.File; import java.io.IOException; import java.net.CookieHandler; @@ -77,19 +76,15 @@ public final class CacheTest { private static final SSLContext sslContext = SslContextBuilder.localhost(); @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); - @Rule public MockWebServerRule serverRule = new MockWebServerRule(); - @Rule public MockWebServerRule server2Rule = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); + @Rule public MockWebServer server2 = new MockWebServer(); private final OkHttpClient client = new OkHttpClient(); - private MockWebServer server; - private MockWebServer server2; private Cache cache; private final CookieManager cookieManager = new CookieManager(); @Before public void setUp() throws Exception { - server = serverRule.get(); server.setProtocolNegotiationEnabled(false); - server2 = server2Rule.get(); cache = new Cache(cacheRule.getRoot(), Integer.MAX_VALUE); client.setCache(cache); CookieHandler.setDefault(cookieManager); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java index d45bbe15b154..44a3ab43d286 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java @@ -23,9 +23,9 @@ import com.squareup.okhttp.internal.Version; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import com.squareup.okhttp.mockwebserver.SocketPolicy; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import com.squareup.okhttp.testing.RecordingHostnameVerifier; import java.io.IOException; import java.io.InputStream; @@ -83,8 +83,8 @@ public final class CallTest { @Rule public final TemporaryFolder tempDir = new TemporaryFolder(); @Rule public final TestRule timeout = new Timeout(30_000); - @Rule public final MockWebServerRule server = new MockWebServerRule(); - @Rule public final MockWebServerRule server2 = new MockWebServerRule(); + @Rule public final MockWebServer server = new MockWebServer(); + @Rule public final MockWebServer server2 = new MockWebServer(); private OkHttpClient client = new OkHttpClient(); private RecordingCallback callback = new RecordingCallback(); private TestLogHandler logHandler = new TestLogHandler(); @@ -761,7 +761,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void tls() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .setBody("abc") .addHeader("Content-Type: text/plain")); @@ -774,7 +774,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void tls_Async() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .setBody("abc") .addHeader("Content-Type: text/plain")); @@ -819,7 +819,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void recoverFromTlsHandshakeFailure() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setBody("abc")); @@ -840,7 +840,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc return; } - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); RecordingSSLSocketFactory clientSocketFactory = @@ -864,7 +864,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void recoverFromTlsHandshakeFailure_Async() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setBody("abc")); @@ -882,7 +882,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc @Test public void noRecoveryFromTlsHandshakeFailureWhenTlsFallbackIsDisabled() throws Exception { client.setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT)); - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); suppressTlsFallbackScsv(client); @@ -917,7 +917,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void setFollowSslRedirectsFalse() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setResponseCode(301).addHeader("Location: http://square.com")); client.setFollowSslRedirects(false); @@ -930,7 +930,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void matchingPinnedCertificate() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse()); server.enqueue(new MockResponse()); @@ -942,7 +942,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc Response response1 = client.newCall(request1).execute(); CertificatePinner.Builder certificatePinnerBuilder = new CertificatePinner.Builder(); for (Certificate certificate : response1.handshake().peerCertificates()) { - certificatePinnerBuilder.add(server.get().getHostName(), CertificatePinner.pin(certificate)); + certificatePinnerBuilder.add(server.getHostName(), CertificatePinner.pin(certificate)); } // Make another request with certificate pinning. It should complete normally. @@ -953,7 +953,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void unmatchingPinnedCertificate() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse()); client.setSslSocketFactory(sslContext.getSocketFactory()); @@ -961,7 +961,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc // Pin publicobject.com's cert. client.setCertificatePinner(new CertificatePinner.Builder() - .add(server.get().getHostName(), "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") + .add(server.getHostName(), "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") .build()); // When we pin the wrong certificate, connectivity fails. @@ -1298,7 +1298,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER); HttpCookie cookie = new HttpCookie("c", "cookie"); - cookie.setDomain(server.get().getCookieDomain()); + cookie.setDomain(server.getCookieDomain()); cookie.setPath("/"); String portList = Integer.toString(server.getPort()); cookie.setPortlist(portList); @@ -1312,7 +1312,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc RecordedRequest request1 = server.takeRequest(); assertEquals("$Version=\"1\"; c=\"cookie\";$Path=\"/\";$Domain=\"" - + server.get().getCookieDomain() + + server.getCookieDomain() + "\";$Port=\"" + portList + "\"", request1.getHeader("Cookie")); @@ -1502,7 +1502,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc } @Test public void cancelInFlightBeforeResponseReadThrowsIOE() throws Exception { - server.get().setDispatcher(new Dispatcher() { + server.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { client.cancel("request"); return new MockResponse().setBody("A"); @@ -1533,7 +1533,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc */ @Test public void canceledBeforeIOSignalsOnFailure() throws Exception { client.getDispatcher().setMaxRequests(1); // Force requests to be executed serially. - server.get().setDispatcher(new Dispatcher() { + server.setDispatcher(new Dispatcher() { char nextResponse = 'A'; @Override public MockResponse dispatch(RecordedRequest request) { @@ -1567,7 +1567,7 @@ private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exc @Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception { Request requestA = new Request.Builder().url(server.url("/a")).tag("request A").build(); final Call call = client.newCall(requestA); - server.get().setDispatcher(new Dispatcher() { + server.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { call.cancel(); return new MockResponse().setBody("A"); @@ -1793,8 +1793,8 @@ private void enableProtocol(Protocol protocol) { client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(new RecordingHostnameVerifier()); client.setProtocols(Arrays.asList(protocol, Protocol.HTTP_1_1)); - server.get().useHttps(sslContext.getSocketFactory(), false); - server.get().setProtocols(client.getProtocols()); + server.useHttps(sslContext.getSocketFactory(), false); + server.setProtocols(client.getProtocols()); } private Buffer gzip(String data) throws IOException { diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/InterceptorTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/InterceptorTest.java index a4ab560020ea..dcfe563ea47d 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/InterceptorTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/InterceptorTest.java @@ -16,8 +16,8 @@ package com.squareup.okhttp; import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.IOException; import java.net.URL; import java.util.Arrays; @@ -46,13 +46,13 @@ import static org.junit.Assert.fail; public final class InterceptorTest { - @Rule public MockWebServerRule server = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); private OkHttpClient client = new OkHttpClient(); private RecordingCallback callback = new RecordingCallback(); @Test public void applicationInterceptorsCanShortCircuitResponses() throws Exception { - server.get().shutdown(); // Accept no connections. + server.shutdown(); // Accept no connections. Request request = new Request.Builder() .url("https://localhost:1/") @@ -185,7 +185,7 @@ public final class InterceptorTest { // The network request has everything: User-Agent, Host, Accept-Encoding. Request networkRequest = chain.request(); assertNotNull(networkRequest.header("User-Agent")); - assertEquals(server.get().getHostName() + ":" + server.get().getPort(), + assertEquals(server.getHostName() + ":" + server.getPort(), networkRequest.header("Host")); assertNotNull(networkRequest.header("Accept-Encoding")); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java index 2126f8c22135..a9fcf035356d 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java @@ -24,9 +24,9 @@ import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.internal.Util; import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import com.squareup.okhttp.mockwebserver.SocketPolicy; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.IOException; import java.io.InputStream; import java.net.Authenticator; @@ -73,7 +73,7 @@ public boolean verify(String hostname, SSLSession session) { }; @Rule public final TemporaryFolder tempDir = new TemporaryFolder(); - @Rule public final MockWebServerRule server = new MockWebServerRule(); + @Rule public final MockWebServer server = new MockWebServer(); /** Protocol to test, for example {@link com.squareup.okhttp.Protocol#SPDY_3} */ private final Protocol protocol; @@ -88,7 +88,7 @@ protected HttpOverSpdyTest(Protocol protocol){ } @Before public void setUp() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); client.client().setProtocols(Arrays.asList(protocol, Protocol.HTTP_1_1)); client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(NULL_HOSTNAME_VERIFIER); @@ -381,7 +381,7 @@ protected HttpOverSpdyTest(Protocol protocol){ client.client().setCookieHandler(cookieManager); server.enqueue(new MockResponse() - .addHeader("set-cookie: c=oreo; domain=" + server.get().getCookieDomain()) + .addHeader("set-cookie: c=oreo; domain=" + server.getCookieDomain()) .setBody("A")); server.enqueue(new MockResponse() .setBody("B")); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/URLConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/URLConnectionTest.java index e4364c034676..f542e73bb38b 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/URLConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/URLConnectionTest.java @@ -41,7 +41,6 @@ import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import com.squareup.okhttp.mockwebserver.SocketPolicy; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import com.squareup.okhttp.testing.RecordingHostnameVerifier; import java.io.IOException; import java.io.InputStream; @@ -116,8 +115,8 @@ public final class URLConnectionTest { private static final SSLContext sslContext = SslContextBuilder.localhost(); - @Rule public final MockWebServerRule server = new MockWebServerRule(); - @Rule public final MockWebServerRule server2 = new MockWebServerRule(); + @Rule public final MockWebServer server = new MockWebServer(); + @Rule public final MockWebServer server2 = new MockWebServer(); @Rule public final TemporaryFolder tempDir = new TemporaryFolder(); private OkUrlFactory client; @@ -125,7 +124,7 @@ public final class URLConnectionTest { private Cache cache; @Before public void setUp() throws Exception { - server.get().setProtocolNegotiationEnabled(false); + server.setProtocolNegotiationEnabled(false); client = new OkUrlFactory(new OkHttpClient()); } @@ -290,7 +289,7 @@ public final class URLConnectionTest { @Test public void connectRetriesUntilConnectedOrFailed() throws Exception { URL url = server.getUrl("/foo"); - server.get().shutdown(); + server.shutdown(); connection = client.open(url); try { @@ -317,9 +316,9 @@ private void testRequestBodySurvivesRetries(TransferKind transferKind) throws Ex // Use a misconfigured proxy to guarantee that the request is retried. FakeProxySelector proxySelector = new FakeProxySelector(); - proxySelector.proxies.add(server2.get().toProxyAddress()); + proxySelector.proxies.add(server2.toProxyAddress()); client.client().setProxySelector(proxySelector); - server2.get().shutdown(); + server2.shutdown(); connection = client.open(server.getUrl("/def")); connection.setDoOutput(true); @@ -467,7 +466,7 @@ enum WriteKind {BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS} private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception { int n = 512 * 1024; - server.get().setBodyLimit(0); + server.setBodyLimit(0); server.enqueue(new MockResponse()); HttpURLConnection conn = client.open(server.getUrl("/")); @@ -517,7 +516,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep } @Test public void connectViaHttps() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -531,7 +530,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep } @Test public void inspectHandshakeThroughoutRequestLifecycle() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse()); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -560,7 +559,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep } @Test public void connectViaHttpsReusingConnections() throws IOException, InterruptedException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS")); @@ -582,7 +581,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep @Test public void connectViaHttpsReusingConnectionsDifferentFactories() throws IOException, InterruptedException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS")); @@ -602,7 +601,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep } @Test public void connectViaHttpsWithSSLFallback() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setBody("this response comes via SSL")); @@ -618,7 +617,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep } @Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); @@ -643,7 +642,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep * https://github.com/square/okhttp/issues/515 */ @Test public void sslFallbackNotUsedWhenRecycledConnectionFails() throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse() .setBody("abc") .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)); @@ -671,7 +670,7 @@ private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Excep * http://code.google.com/p/android/issues/detail?id=13178 */ @Test public void connectViaHttpsToUntrustedServer() throws IOException, InterruptedException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse()); // unused connection = client.open(server.getUrl("/foo")); @@ -701,11 +700,11 @@ private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception { server.enqueue(mockResponse); URL url = new URL("http://android.com/foo"); - connection = proxyConfig.connect(server.get(), client, url); + connection = proxyConfig.connect(server, client, url); assertContent("this response comes via a proxy", connection); assertTrue(connection.usingProxy()); - RecordedRequest request = server.get().takeRequest(); + RecordedRequest request = server.takeRequest(); assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine()); assertEquals("android.com", request.getHeader("Host")); } @@ -741,7 +740,7 @@ public Socket createSocket(String host, int port, InetAddress localHost, int loc }; if (useHttps) { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(new RecordingHostnameVerifier()); } @@ -815,13 +814,13 @@ public Socket createSocket(String host, int port, InetAddress localHost, int loc } private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); URL url = server.getUrl("/foo"); client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(new RecordingHostnameVerifier()); - connection = proxyConfig.connect(server.get(), client, url); + connection = proxyConfig.connect(server, client, url); assertContent("this response comes via HTTPS", connection); @@ -852,7 +851,7 @@ private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Ex private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); - server.get().useHttps(sslContext.getSocketFactory(), true); + server.useHttps(sslContext.getSocketFactory(), true); server.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("this response comes via a secure proxy")); @@ -860,7 +859,7 @@ private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exce URL url = new URL("https://android.com/foo"); client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(hostnameVerifier); - connection = proxyConfig.connect(server.get(), client, url); + connection = proxyConfig.connect(server, client, url); assertContent("this response comes via a secure proxy", connection); @@ -879,7 +878,7 @@ private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exce @Test public void connectViaHttpProxyToHttpsUsingBadProxyAndHttpResponseCache() throws Exception { initResponseCache(); - server.get().useHttps(sslContext.getSocketFactory(), true); + server.useHttps(sslContext.getSocketFactory(), true); // The inclusion of a body in the response to a CONNECT is key to reproducing b/6754912. MockResponse badProxyResponse = new MockResponse() .setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END) @@ -893,7 +892,7 @@ private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exce client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setConnectionSpecs(Util.immutableList(ConnectionSpec.MODERN_TLS)); client.client().setHostnameVerifier(new RecordingHostnameVerifier()); - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); URL url = new URL("https://android.com/foo"); connection = client.open(url); @@ -914,12 +913,12 @@ private void initResponseCache() throws IOException { throws IOException, InterruptedException { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); - server.get().useHttps(sslContext.getSocketFactory(), true); + server.useHttps(sslContext.getSocketFactory(), true); server.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("encrypted response from the origin server")); - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); URL url = new URL("https://android.com/foo"); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -944,14 +943,14 @@ private void initResponseCache() throws IOException { @Test public void proxyAuthenticateOnConnect() throws Exception { Authenticator.setDefault(new RecordingAuthenticator()); - server.get().useHttps(sslContext.getSocketFactory(), true); + server.useHttps(sslContext.getSocketFactory(), true); server.enqueue(new MockResponse().setResponseCode(407) .addHeader("Proxy-Authenticate: Basic realm=\"localhost\"")); server.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("A")); - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); URL url = new URL("https://android.com/foo"); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -976,12 +975,12 @@ private void initResponseCache() throws IOException { // Don't disconnect after building a tunnel with CONNECT // http://code.google.com/p/android/issues/detail?id=37221 @Test public void proxyWithConnectionClose() throws IOException { - server.get().useHttps(sslContext.getSocketFactory(), true); + server.useHttps(sslContext.getSocketFactory(), true); server.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("this response comes via a proxy")); - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); URL url = new URL("https://android.com/foo"); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -996,13 +995,13 @@ private void initResponseCache() throws IOException { SSLSocketFactory socketFactory = sslContext.getSocketFactory(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); - server.get().useHttps(socketFactory, true); + server.useHttps(socketFactory, true); server.enqueue( new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders()); server.enqueue(new MockResponse().setBody("response 1")); server.enqueue(new MockResponse().setBody("response 2")); - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); URL url = new URL("https://android.com/foo"); client.client().setSslSocketFactory(socketFactory); @@ -1238,7 +1237,7 @@ private void testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferK if (tls) { SSLSocketFactory socketFactory = sslContext.getSocketFactory(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); - server.get().useHttps(socketFactory, false); + server.useHttps(socketFactory, false); client.client().setSslSocketFactory(socketFactory); client.client().setHostnameVerifier(hostnameVerifier); } @@ -1523,7 +1522,7 @@ private List authCallsForHeader(String authHeader) throws IOException { server.enqueue(pleaseAuthenticate); if (proxy) { - client.client().setProxy(server.get().toProxyAddress()); + client.client().setProxy(server.toProxyAddress()); connection = client.open(new URL("http://android.com")); } else { connection = client.open(server.getUrl("/")); @@ -1660,7 +1659,7 @@ private void assertInvalidRequestMethod(String requestMethod) throws Exception { * http://code.google.com/p/android/issues/detail?id=12860 */ private void testSecureStreamingPost(StreamingMode streamingMode) throws Exception { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("Success!")); client.client().setSslSocketFactory(sslContext.getSocketFactory()); @@ -1831,7 +1830,7 @@ private void testRedirected(TransferKind transferKind, boolean reuse) throws Exc } @Test public void redirectedOnHttps() throws IOException, InterruptedException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo") .setBody("This page has moved!")); @@ -1851,7 +1850,7 @@ private void testRedirected(TransferKind transferKind, boolean reuse) throws Exc } @Test public void notRedirectedFromHttpsToHttp() throws IOException, InterruptedException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: http://anyhost/foo") .setBody("This page has moved!")); @@ -1876,7 +1875,7 @@ private void testRedirected(TransferKind transferKind, boolean reuse) throws Exc @Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception { server2.enqueue(new MockResponse().setBody("This is insecure HTTP!")); - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: " + server2.getUrl("/")) .setBody("This page has moved!")); @@ -1894,7 +1893,7 @@ private void testRedirected(TransferKind transferKind, boolean reuse) throws Exc } @Test public void redirectedFromHttpToHttpsFollowingProtocolRedirects() throws Exception { - server2.get().useHttps(sslContext.getSocketFactory(), false); + server2.useHttps(sslContext.getSocketFactory(), false); server2.enqueue(new MockResponse().setBody("This is secure HTTPS!")); server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) @@ -1919,9 +1918,9 @@ private void testRedirected(TransferKind transferKind, boolean reuse) throws Exc private void redirectToAnotherOriginServer(boolean https) throws Exception { if (https) { - server.get().useHttps(sslContext.getSocketFactory(), false); - server2.get().useHttps(sslContext.getSocketFactory(), false); - server2.get().setProtocolNegotiationEnabled(false); + server.useHttps(sslContext.getSocketFactory(), false); + server2.useHttps(sslContext.getSocketFactory(), false); + server2.setProtocolNegotiationEnabled(false); client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(new RecordingHostnameVerifier()); } @@ -1942,8 +1941,8 @@ private void redirectToAnotherOriginServer(boolean https) throws Exception { assertContent("This is the first server again!", client.open(server.getUrl("/"))); assertContent("This is the 2nd server, again!", client.open(server2.getUrl("/"))); - String server1Host = server.get().getHostName() + ":" + server.getPort(); - String server2Host = server2.get().getHostName() + ":" + server2.getPort(); + String server1Host = server.getHostName() + ":" + server.getPort(); + String server2Host = server2.getHostName() + ":" + server2.getPort(); assertEquals(server1Host, server.takeRequest().getHeader("Host")); assertEquals(server2Host, server2.takeRequest().getHeader("Host")); assertEquals("Expected connection reuse", 1, server.takeRequest().getSequenceNumber()); @@ -1955,9 +1954,9 @@ private void redirectToAnotherOriginServer(boolean https) throws Exception { client.client().setProxySelector(new ProxySelector() { @Override public List select(URI uri) { proxySelectionRequests.add(uri); - MockWebServer proxyServer = (uri.getPort() == server.get().getPort()) - ? server.get() - : server2.get(); + MockWebServer proxyServer = (uri.getPort() == server.getPort()) + ? server + : server2; return Arrays.asList(proxyServer.toProxyAddress()); } @@ -2202,7 +2201,7 @@ private void testRedirect(boolean temporary, String method) throws Exception { client.client().setHostnameVerifier(hostnameVerifier); client.client().setSslSocketFactory(sc.getSocketFactory()); - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("ABC")); server.enqueue(new MockResponse().setBody("DEF")); server.enqueue(new MockResponse().setBody("GHI")); @@ -2212,9 +2211,9 @@ private void testRedirect(boolean temporary, String method) throws Exception { assertContent("DEF", client.open(url)); assertContent("GHI", client.open(url)); - assertEquals(Arrays.asList("verify " + server.get().getHostName()), + assertEquals(Arrays.asList("verify " + server.getHostName()), hostnameVerifier.calls); - assertEquals(Arrays.asList("checkServerTrusted [CN=" + server.get().getHostName() + " 1]"), + assertEquals(Arrays.asList("checkServerTrusted [CN=" + server.getHostName() + " 1]"), trustManager.calls); } @@ -2245,7 +2244,7 @@ private void testRedirect(boolean temporary, String method) throws Exception { // Sockets on some platforms can have large buffers that mean writes do not block when // required. These socket factories explicitly set the buffer sizes on sockets created. final int SOCKET_BUFFER_SIZE = 256 * 1024; - server.get().setServerSocketFactory( + server.setServerSocketFactory( new DelegatingServerSocketFactory(ServerSocketFactory.getDefault()) { @Override protected void configureServerSocket(ServerSocket serverSocket) throws IOException { @@ -2452,11 +2451,11 @@ private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws I server.enqueue(new MockResponse().setBody("ABC")); // The request should work once and then fail - HttpURLConnection connection1 = client.open(server.getUrl("")); + HttpURLConnection connection1 = client.open(server.getUrl("/")); connection1.setReadTimeout(100); InputStream input = connection1.getInputStream(); assertEquals("ABC", readAscii(input, Integer.MAX_VALUE)); - server.get().shutdown(); + server.shutdown(); try { HttpURLConnection connection2 = client.open(server.getUrl("")); connection2.setReadTimeout(100); @@ -2575,7 +2574,7 @@ private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws I @Test public void urlContainsQueryButNoPath() throws Exception { server.enqueue(new MockResponse().setBody("A")); - URL url = new URL("http", server.get().getHostName(), server.getPort(), "?query"); + URL url = new URL("http", server.getHostName(), server.getPort(), "?query"); assertEquals("A", readAscii(client.open(url).getInputStream(), Integer.MAX_VALUE)); RecordedRequest request = server.takeRequest(); assertEquals("GET /?query HTTP/1.1", request.getRequestLine()); @@ -3018,7 +3017,7 @@ private void zeroLengthPayload(String method) } @Test public void veryLargeFixedLengthRequest() throws Exception { - server.get().setBodyLimit(0); + server.setBodyLimit(0); server.enqueue(new MockResponse()); connection = client.open(server.getUrl("/")); @@ -3303,9 +3302,9 @@ private void enableProtocol(Protocol protocol) { client.client().setSslSocketFactory(sslContext.getSocketFactory()); client.client().setHostnameVerifier(new RecordingHostnameVerifier()); client.client().setProtocols(Arrays.asList(protocol, Protocol.HTTP_1_1)); - server.get().useHttps(sslContext.getSocketFactory(), false); - server.get().setProtocolNegotiationEnabled(true); - server.get().setProtocols(client.client().getProtocols()); + server.useHttps(sslContext.getSocketFactory(), false); + server.setProtocolNegotiationEnabled(true); + server.setProtocols(client.client().getProtocols()); } /** diff --git a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/OkUrlFactoryTest.java b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/OkUrlFactoryTest.java index a7dc44b0d0dd..86d9be90e8e7 100644 --- a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/OkUrlFactoryTest.java +++ b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/OkUrlFactoryTest.java @@ -3,7 +3,6 @@ import com.squareup.okhttp.internal.Platform; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import java.io.IOException; import java.net.HttpURLConnection; import java.text.DateFormat; @@ -24,15 +23,12 @@ import static org.junit.Assert.fail; public class OkUrlFactoryTest { - @Rule public MockWebServerRule serverRule = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); @Rule public TemporaryFolder cacheFolder = new TemporaryFolder(); - private MockWebServer server; private OkUrlFactory factory; @Before public void setUp() throws IOException { - server = serverRule.get(); - OkHttpClient client = new OkHttpClient(); client.setCache(new Cache(cacheFolder.getRoot(), 10 * 1024 * 1024)); factory = new OkUrlFactory(client); diff --git a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java index db0ed8fa6c30..4db5637b5703 100644 --- a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java +++ b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java @@ -22,7 +22,6 @@ import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; import okio.Buffer; import okio.BufferedSink; import okio.GzipSink; @@ -83,19 +82,15 @@ public final class UrlConnectionCacheTest { private static final SSLContext sslContext = SslContextBuilder.localhost(); @Rule public TemporaryFolder cacheRule = new TemporaryFolder(); - @Rule public MockWebServerRule serverRule = new MockWebServerRule(); - @Rule public MockWebServerRule server2Rule = new MockWebServerRule(); + @Rule public MockWebServer server = new MockWebServer(); + @Rule public MockWebServer server2 = new MockWebServer(); private final OkUrlFactory client = new OkUrlFactory(new OkHttpClient()); - private MockWebServer server; - private MockWebServer server2; private Cache cache; private final CookieManager cookieManager = new CookieManager(); @Before public void setUp() throws Exception { - server = serverRule.get(); server.setProtocolNegotiationEnabled(false); - server2 = server2Rule.get(); cache = new Cache(cacheRule.getRoot(), Integer.MAX_VALUE); client.client().setCache(cache); CookieHandler.setDefault(cookieManager); diff --git a/okhttp-ws-tests/src/test/java/com/squareup/okhttp/ws/WebSocketCallTest.java b/okhttp-ws-tests/src/test/java/com/squareup/okhttp/ws/WebSocketCallTest.java index 07c82f49573b..ee2aad7f6cd6 100644 --- a/okhttp-ws-tests/src/test/java/com/squareup/okhttp/ws/WebSocketCallTest.java +++ b/okhttp-ws-tests/src/test/java/com/squareup/okhttp/ws/WebSocketCallTest.java @@ -20,7 +20,7 @@ import com.squareup.okhttp.Response; import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.mockwebserver.MockResponse; -import com.squareup.okhttp.mockwebserver.rule.MockWebServerRule; +import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.testing.RecordingHostnameVerifier; import java.io.IOException; import java.net.ProtocolException; @@ -40,7 +40,7 @@ public final class WebSocketCallTest { private static final SSLContext sslContext = SslContextBuilder.localhost(); - @Rule public final MockWebServerRule server = new MockWebServerRule(); + @Rule public final MockWebServer server = new MockWebServer(); private final WebSocketRecorder listener = new WebSocketRecorder(); private final OkHttpClient client = new OkHttpClient(); @@ -209,7 +209,7 @@ public final class WebSocketCallTest { } @Test public void wssScheme() throws IOException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(new RecordingHostnameVerifier()); @@ -217,7 +217,7 @@ public final class WebSocketCallTest { } @Test public void httpsScheme() throws IOException { - server.get().useHttps(sslContext.getSocketFactory(), false); + server.useHttps(sslContext.getSocketFactory(), false); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(new RecordingHostnameVerifier());