Skip to content

Commit

Permalink
Merge pull request square#1765 from square/jw/make-mws-rule-just-a-mw…
Browse files Browse the repository at this point in the history
…s-instance

Fold MockWebServerRule into MockWebServer.
  • Loading branch information
swankjesse committed Jul 24, 2015
2 parents 291870e + 8f5e344 commit ad4b328
Show file tree
Hide file tree
Showing 16 changed files with 201 additions and 355 deletions.
1 change: 0 additions & 1 deletion mockwebserver/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -127,44 +129,61 @@ public final class MockWebServer {
private List<Protocol> 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();
}

/**
Expand All @@ -177,8 +196,8 @@ public HttpUrl url(String path) {
.scheme(sslSocketFactory != null ? "https" : "http")
.host(getHostName())
.port(getPort())
.encodedPath(path)
.build();
.build()
.resolve(path);
}

/**
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -927,7 +939,7 @@ private void pushPromises(FramedStream stream, List<PushPromise> promises) throw
List<Header> 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();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand All @@ -279,16 +277,53 @@ private List<String> 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 {
MockWebServer server = new MockWebServer();
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) {
}
}
}
Loading

0 comments on commit ad4b328

Please sign in to comment.