1
0
mirror of https://github.com/square/okhttp.git synced 2026-01-25 16:01:38 +03:00

Merge branch 'mockwebserver' into jwilson/import_mockwebserver

This commit is contained in:
jwilson
2013-08-04 09:03:29 -04:00
9 changed files with 1760 additions and 0 deletions

202
mockwebserver/COPYING Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2012 Google 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.google.mockwebserver;
/**
* Handler for mock server requests.
*/
public abstract class Dispatcher {
/**
* Returns a response to satisfy {@code request}. This method may block (for
* instance, to wait on a CountdownLatch).
*/
public abstract MockResponse dispatch(RecordedRequest request) throws InterruptedException;
/**
* Returns the socket policy of the next request. Default implementation
* returns {@link SocketPolicy#KEEP_OPEN}. Mischievous implementations can
* return other values to test HTTP edge cases.
*/
public SocketPolicy peekSocketPolicy() {
return SocketPolicy.KEEP_OPEN;
}
}

View File

@@ -0,0 +1,240 @@
/*
* Copyright (C) 2011 Google 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.google.mockwebserver;
import static com.google.mockwebserver.MockWebServer.ASCII;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A scripted response to be replayed by the mock web server.
*/
public final class MockResponse implements Cloneable {
private static final String CHUNKED_BODY_HEADER = "Transfer-encoding: chunked";
private String status = "HTTP/1.1 200 OK";
private List<String> headers = new ArrayList<String>();
/** The response body content, or null if {@code bodyStream} is set. */
private byte[] body;
/** The response body content, or null if {@code body} is set. */
private InputStream bodyStream;
private int bytesPerSecond = Integer.MAX_VALUE;
private SocketPolicy socketPolicy = SocketPolicy.KEEP_OPEN;
/**
* Creates a new mock response with an empty body.
*/
public MockResponse() {
setBody(new byte[0]);
}
@Override public MockResponse clone() {
try {
MockResponse result = (MockResponse) super.clone();
result.headers = new ArrayList<String>(result.headers);
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
/**
* Returns the HTTP response line, such as "HTTP/1.1 200 OK".
*/
public String getStatus() {
return status;
}
public MockResponse setResponseCode(int code) {
this.status = "HTTP/1.1 " + code + " OK";
return this;
}
public MockResponse setStatus(String status) {
this.status = status;
return this;
}
/**
* Returns the HTTP headers, such as "Content-Length: 0".
*/
public List<String> getHeaders() {
return headers;
}
/**
* Removes all HTTP headers including any "Content-Length" and
* "Transfer-encoding" headers that were added by default.
*/
public MockResponse clearHeaders() {
headers.clear();
return this;
}
/**
* Adds {@code header} as an HTTP header. For well-formed HTTP {@code
* header} should contain a name followed by a colon and a value.
*/
public MockResponse addHeader(String header) {
headers.add(header);
return this;
}
/**
* Adds a new header with the name and value. This may be used to add
* multiple headers with the same name.
*/
public MockResponse addHeader(String name, Object value) {
return addHeader(name + ": " + String.valueOf(value));
}
/**
* Removes all headers named {@code name}, then adds a new header with the
* name and value.
*/
public MockResponse setHeader(String name, Object value) {
removeHeader(name);
return addHeader(name, value);
}
/**
* Removes all headers named {@code name}.
*/
public MockResponse removeHeader(String name) {
name += ":";
for (Iterator<String> i = headers.iterator(); i.hasNext(); ) {
String header = i.next();
if (name.regionMatches(true, 0, header, 0, name.length())) {
i.remove();
}
}
return this;
}
/**
* Returns the raw HTTP payload, or null if this response is streamed.
*/
public byte[] getBody() {
return body;
}
/**
* Returns an input stream containing the raw HTTP payload.
*/
InputStream getBodyStream() {
return bodyStream != null ? bodyStream : new ByteArrayInputStream(body);
}
public MockResponse setBody(byte[] body) {
setHeader("Content-Length", body.length);
this.body = body;
this.bodyStream = null;
return this;
}
public MockResponse setBody(InputStream bodyStream, long bodyLength) {
setHeader("Content-Length", bodyLength);
this.body = null;
this.bodyStream = bodyStream;
return this;
}
/**
* Sets the response body to the UTF-8 encoded bytes of {@code body}.
*/
public MockResponse setBody(String body) {
try {
return setBody(body.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
}
/**
* Sets the response body to {@code body}, chunked every {@code
* maxChunkSize} bytes.
*/
public MockResponse setChunkedBody(byte[] body, int maxChunkSize) {
removeHeader("Content-Length");
headers.add(CHUNKED_BODY_HEADER);
try {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
int pos = 0;
while (pos < body.length) {
int chunkSize = Math.min(body.length - pos, maxChunkSize);
bytesOut.write(Integer.toHexString(chunkSize).getBytes(ASCII));
bytesOut.write("\r\n".getBytes(ASCII));
bytesOut.write(body, pos, chunkSize);
bytesOut.write("\r\n".getBytes(ASCII));
pos += chunkSize;
}
bytesOut.write("0\r\n\r\n".getBytes(ASCII)); // last chunk + empty trailer + crlf
this.body = bytesOut.toByteArray();
return this;
} catch (IOException e) {
throw new AssertionError(); // In-memory I/O doesn't throw IOExceptions.
}
}
/**
* Sets the response body to the UTF-8 encoded bytes of {@code body},
* chunked every {@code maxChunkSize} bytes.
*/
public MockResponse setChunkedBody(String body, int maxChunkSize) {
try {
return setChunkedBody(body.getBytes("UTF-8"), maxChunkSize);
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
}
public SocketPolicy getSocketPolicy() {
return socketPolicy;
}
public MockResponse setSocketPolicy(SocketPolicy socketPolicy) {
this.socketPolicy = socketPolicy;
return this;
}
public int getBytesPerSecond() {
return bytesPerSecond;
}
/**
* Set simulated network speed, in bytes per second. This applies to the
* response body only; response headers are not throttled.
*/
public MockResponse setBytesPerSecond(int bytesPerSecond) {
this.bytesPerSecond = bytesPerSecond;
return this;
}
@Override public String toString() {
return status;
}
}

View File

@@ -0,0 +1,585 @@
/*
* Copyright (C) 2011 Google 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.google.mockwebserver;
import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START;
import static com.google.mockwebserver.SocketPolicy.FAIL_HANDSHAKE;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* A scriptable web server. Callers supply canned responses and the server
* replays them upon request in sequence.
*/
public final class MockWebServer {
static final String ASCII = "US-ASCII";
private static final Logger logger = Logger.getLogger(MockWebServer.class.getName());
private final BlockingQueue<RecordedRequest> requestQueue
= new LinkedBlockingQueue<RecordedRequest>();
/** All map values are Boolean.TRUE. (Collections.newSetFromMap isn't available in Froyo) */
private final Map<Socket, Boolean> openClientSockets = new ConcurrentHashMap<Socket, Boolean>();
private final AtomicInteger requestCount = new AtomicInteger();
private int bodyLimit = Integer.MAX_VALUE;
private ServerSocket serverSocket;
private SSLSocketFactory sslSocketFactory;
private ExecutorService executor;
private boolean tunnelProxy;
private Dispatcher dispatcher = new QueueDispatcher();
private int port = -1;
public int getPort() {
if (port == -1) {
throw new IllegalStateException("Cannot retrieve port before calling play()");
}
return port;
}
public String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
throw new AssertionError(e);
}
}
public Proxy toProxyAddress() {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getHostName(), getPort()));
}
/**
* Returns a URL for connecting to this server.
*
* @param path the request path, such as "/".
*/
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);
}
}
/**
* Returns a cookie domain for this server. This returns the server's
* non-loopback host name if it is known. Otherwise this returns ".local"
* for this server's loopback name.
*/
public String getCookieDomain() {
String hostName = getHostName();
return hostName.contains(".") ? hostName : ".local";
}
/**
* Sets the number of bytes of the POST body to keep in memory to the given
* limit.
*/
public void setBodyLimit(int maxBodyLength) {
this.bodyLimit = maxBodyLength;
}
/**
* Serve requests with HTTPS rather than otherwise.
*
* @param tunnelProxy whether to expect the HTTP CONNECT method before
* negotiating TLS.
*/
public void useHttps(SSLSocketFactory sslSocketFactory, boolean tunnelProxy) {
this.sslSocketFactory = sslSocketFactory;
this.tunnelProxy = tunnelProxy;
}
/**
* Awaits the next HTTP request, removes it, and returns it. Callers should
* use this to verify the request sent was as intended.
*/
public RecordedRequest takeRequest() throws InterruptedException {
return requestQueue.take();
}
/**
* Returns the number of HTTP requests received thus far by this server.
* This may exceed the number of HTTP connections when connection reuse is
* in practice.
*/
public int getRequestCount() {
return requestCount.get();
}
/**
* Scripts {@code response} to be returned to a request made in sequence.
* The first request is served by the first enqueued response; the second
* request by the second enqueued response; and so on.
*
* @throws ClassCastException if the default dispatcher has been replaced
* with {@link #setDispatcher(Dispatcher)}.
*/
public void enqueue(MockResponse response) {
((QueueDispatcher) dispatcher).enqueueResponse(response.clone());
}
/**
* Equivalent to {@code play(0)}.
*/
public void play() throws IOException {
play(0);
}
/**
* Starts the server, serves all enqueued requests, and shuts the server
* down.
*
* @param port the port to listen to, or 0 for any available port.
* Automated tests should always use port 0 to avoid flakiness when a
* specific port is unavailable.
*/
public void play(int port) throws IOException {
if (executor != null) {
throw new IllegalStateException("play() already called");
}
executor = Executors.newCachedThreadPool();
serverSocket = new ServerSocket(port);
serverSocket.setReuseAddress(true);
this.port = serverSocket.getLocalPort();
executor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() {
public void run() {
try {
acceptConnections();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer connection failed", e);
}
/*
* This gnarly block of code will release all sockets and
* all thread, even if any close fails.
*/
try {
serverSocket.close();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer server socket close failed", e);
}
for (Iterator<Socket> s = openClientSockets.keySet().iterator(); s.hasNext(); ) {
try {
s.next().close();
s.remove();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer socket close failed", e);
}
}
try {
executor.shutdown();
} catch (Throwable e) {
logger.log(Level.WARNING, "MockWebServer executor shutdown failed", e);
}
}
private void acceptConnections() throws Exception {
while (true) {
Socket socket;
try {
socket = serverSocket.accept();
} catch (SocketException e) {
return;
}
final SocketPolicy socketPolicy = dispatcher.peekSocketPolicy();
if (socketPolicy == DISCONNECT_AT_START) {
dispatchBookkeepingRequest(0, socket);
socket.close();
} else {
openClientSockets.put(socket, true);
serveConnection(socket);
}
}
}
}));
}
public void shutdown() throws IOException {
if (serverSocket != null) {
serverSocket.close(); // should cause acceptConnections() to break out
}
}
private void serveConnection(final Socket raw) {
String name = "MockWebServer-" + raw.getRemoteSocketAddress();
executor.execute(namedRunnable(name, new Runnable() {
int sequenceNumber = 0;
public void run() {
try {
processConnection();
} catch (Exception e) {
logger.log(Level.WARNING, "MockWebServer connection failed", e);
}
}
public void processConnection() throws Exception {
Socket socket;
if (sslSocketFactory != null) {
if (tunnelProxy) {
createTunnel();
}
final SocketPolicy socketPolicy = dispatcher.peekSocketPolicy();
if (socketPolicy == FAIL_HANDSHAKE) {
dispatchBookkeepingRequest(sequenceNumber, raw);
processHandshakeFailure(raw, sequenceNumber++);
return;
}
socket = sslSocketFactory.createSocket(
raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
((SSLSocket) socket).setUseClientMode(false);
openClientSockets.put(socket, true);
openClientSockets.remove(raw);
} else {
socket = raw;
}
InputStream in = new BufferedInputStream(socket.getInputStream());
OutputStream out = new BufferedOutputStream(socket.getOutputStream());
while (processOneRequest(socket, in, out)) {
}
if (sequenceNumber == 0) {
logger.warning("MockWebServer connection didn't make a request");
}
in.close();
out.close();
socket.close();
openClientSockets.remove(socket);
}
/**
* Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response
* is dispatched.
*/
private void createTunnel() throws IOException, InterruptedException {
while (true) {
final SocketPolicy socketPolicy = dispatcher.peekSocketPolicy();
if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) {
throw new IllegalStateException("Tunnel without any CONNECT!");
}
if (socketPolicy == SocketPolicy.UPGRADE_TO_SSL_AT_END) {
return;
}
}
}
/**
* Reads a request and writes its response. Returns true if a request
* was processed.
*/
private boolean processOneRequest(Socket socket, InputStream in, OutputStream out)
throws IOException, InterruptedException {
RecordedRequest request = readRequest(socket, in, out, sequenceNumber);
if (request == null) {
return false;
}
requestCount.incrementAndGet();
requestQueue.add(request);
MockResponse response = dispatcher.dispatch(request);
writeResponse(out, response);
if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) {
in.close();
out.close();
} else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) {
socket.shutdownInput();
} else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) {
socket.shutdownOutput();
}
logger.info("Received request: " + request + " and responded: " + response);
sequenceNumber++;
return true;
}
}));
}
private void processHandshakeFailure(Socket raw, int sequenceNumber) throws Exception {
X509TrustManager untrusted = new X509TrustManager() {
@Override public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new CertificateException();
}
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) {
throw new AssertionError();
}
@Override public X509Certificate[] getAcceptedIssuers() {
throw new AssertionError();
}
};
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { untrusted }, new java.security.SecureRandom());
SSLSocketFactory sslSocketFactory = context.getSocketFactory();
SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
try {
socket.startHandshake(); // we're testing a handshake failure
throw new AssertionError();
} catch (IOException expected) {
}
socket.close();
}
private void dispatchBookkeepingRequest(int sequenceNumber, Socket socket) throws InterruptedException {
requestCount.incrementAndGet();
dispatcher.dispatch(new RecordedRequest(null, null, null, -1, null, sequenceNumber, socket));
}
/**
* @param sequenceNumber the index of this request on this connection.
*/
private RecordedRequest readRequest(Socket socket, InputStream in, OutputStream out, int sequenceNumber)
throws IOException {
String request;
try {
request = readAsciiUntilCrlf(in);
} catch (IOException streamIsClosed) {
return null; // no request because we closed the stream
}
if (request.length() == 0) {
return null; // no request because the stream is exhausted
}
List<String> headers = new ArrayList<String>();
long contentLength = -1;
boolean chunked = false;
boolean expectContinue = false;
String header;
while ((header = readAsciiUntilCrlf(in)).length() != 0) {
headers.add(header);
String lowercaseHeader = header.toLowerCase();
if (contentLength == -1 && lowercaseHeader.startsWith("content-length:")) {
contentLength = Long.parseLong(header.substring(15).trim());
}
if (lowercaseHeader.startsWith("transfer-encoding:") &&
lowercaseHeader.substring(18).trim().equals("chunked")) {
chunked = true;
}
if (lowercaseHeader.startsWith("expect:") &&
lowercaseHeader.substring(7).trim().equals("100-continue")) {
expectContinue = true;
}
}
if (expectContinue) {
out.write(("HTTP/1.1 100 Continue\r\n").getBytes(ASCII));
out.write(("Content-Length: 0\r\n").getBytes(ASCII));
out.write(("\r\n").getBytes(ASCII));
out.flush();
}
boolean hasBody = false;
TruncatingOutputStream requestBody = new TruncatingOutputStream();
List<Integer> chunkSizes = new ArrayList<Integer>();
if (contentLength != -1) {
hasBody = true;
transfer(contentLength, in, requestBody);
} else if (chunked) {
hasBody = true;
while (true) {
int chunkSize = Integer.parseInt(readAsciiUntilCrlf(in).trim(), 16);
if (chunkSize == 0) {
readEmptyLine(in);
break;
}
chunkSizes.add(chunkSize);
transfer(chunkSize, in, requestBody);
readEmptyLine(in);
}
}
if (request.startsWith("OPTIONS ") || request.startsWith("GET ")
|| request.startsWith("HEAD ") || request.startsWith("DELETE ")
|| request.startsWith("TRACE ") || request.startsWith("CONNECT ")) {
if (hasBody) {
throw new IllegalArgumentException("Request must not have a body: " + request);
}
} else if (!request.startsWith("POST ") && !request.startsWith("PUT ")) {
throw new UnsupportedOperationException("Unexpected method: " + request);
}
return new RecordedRequest(request, headers, chunkSizes,
requestBody.numBytesReceived, requestBody.toByteArray(), sequenceNumber, socket);
}
private void writeResponse(OutputStream out, MockResponse response) throws IOException {
out.write((response.getStatus() + "\r\n").getBytes(ASCII));
for (String header : response.getHeaders()) {
out.write((header + "\r\n").getBytes(ASCII));
}
out.write(("\r\n").getBytes(ASCII));
out.flush();
final InputStream in = response.getBodyStream();
if (in == null) {
return;
}
final int bytesPerSecond = response.getBytesPerSecond();
// Stream data in MTU-sized increments, with a minimum of one packet per second.
final byte[] buffer = bytesPerSecond >= 1452
? new byte[1452]
: new byte[bytesPerSecond];
final long delayMs;
if (bytesPerSecond == Integer.MAX_VALUE) {
delayMs = 0;
} else {
delayMs = (1000 * buffer.length) / bytesPerSecond;
}
int read;
long sinceDelay = 0;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
out.flush();
sinceDelay += read;
if (sinceDelay >= buffer.length && delayMs > 0) {
sinceDelay %= buffer.length;
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
throw new AssertionError();
}
}
}
}
/**
* Transfer bytes from {@code in} to {@code out} until either {@code length}
* bytes have been transferred or {@code in} is exhausted.
*/
private void transfer(long length, InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (length > 0) {
int count = in.read(buffer, 0, (int) Math.min(buffer.length, length));
if (count == -1) {
return;
}
out.write(buffer, 0, count);
length -= count;
}
}
/**
* Returns the text from {@code in} until the next "\r\n", or null if
* {@code in} is exhausted.
*/
private String readAsciiUntilCrlf(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
while (true) {
int c = in.read();
if (c == '\n' && builder.length() > 0 && builder.charAt(builder.length() - 1) == '\r') {
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
} else if (c == -1) {
return builder.toString();
} else {
builder.append((char) c);
}
}
}
private void readEmptyLine(InputStream in) throws IOException {
String line = readAsciiUntilCrlf(in);
if (line.length() != 0) {
throw new IllegalStateException("Expected empty but was: " + line);
}
}
/**
* Sets the dispatcher used to match incoming requests to mock responses.
* The default dispatcher simply serves a fixed sequence of responses from
* a {@link #enqueue(MockResponse) queue}; custom dispatchers can vary the
* response based on timing or the content of the request.
*/
public void setDispatcher(Dispatcher dispatcher) {
if (dispatcher == null) {
throw new NullPointerException();
}
this.dispatcher = dispatcher;
}
/**
* An output stream that drops data after bodyLimit bytes.
*/
private class TruncatingOutputStream extends ByteArrayOutputStream {
private long numBytesReceived = 0;
@Override public void write(byte[] buffer, int offset, int len) {
numBytesReceived += len;
super.write(buffer, offset, Math.min(len, bodyLimit - count));
}
@Override public void write(int oneByte) {
numBytesReceived++;
if (count < bodyLimit) {
super.write(oneByte);
}
}
}
private static Runnable namedRunnable(final String name, final Runnable runnable) {
return new Runnable() {
public void run() {
String originalName = Thread.currentThread().getName();
Thread.currentThread().setName(name);
try {
runnable.run();
} finally {
Thread.currentThread().setName(originalName);
}
}
};
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2012 Google 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.google.mockwebserver;
import java.net.HttpURLConnection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Default dispatcher that processes a script of responses. Populate the script by calling
* {@link #enqueueResponse(MockResponse)}.
*/
public class QueueDispatcher extends Dispatcher {
protected final BlockingQueue<MockResponse> responseQueue
= new LinkedBlockingQueue<MockResponse>();
private MockResponse failFastResponse;
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
// to permit interactive/browser testing, ignore requests for favicons
final String requestLine = request.getRequestLine();
if (requestLine != null && requestLine.equals("GET /favicon.ico HTTP/1.1")) {
System.out.println("served " + requestLine);
return new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
}
if (failFastResponse != null && responseQueue.peek() == null) {
// Fail fast if there's no response queued up.
return failFastResponse;
}
return responseQueue.take();
}
@Override public SocketPolicy peekSocketPolicy() {
MockResponse peek = responseQueue.peek();
if (peek == null) {
return failFastResponse != null
? failFastResponse.getSocketPolicy()
: SocketPolicy.KEEP_OPEN;
}
return peek.getSocketPolicy();
}
public void enqueueResponse(MockResponse response) {
responseQueue.add(response);
}
public void setFailFast(boolean failFast) {
MockResponse failFastResponse = failFast
? new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
: null;
setFailFast(failFastResponse);
}
public void setFailFast(MockResponse failFastResponse) {
this.failFastResponse = failFastResponse;
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright (C) 2011 Google 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.google.mockwebserver;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLSocket;
/**
* An HTTP request that came into the mock web server.
*/
public final class RecordedRequest {
private final String requestLine;
private final String method;
private final String path;
private final List<String> headers;
private final List<Integer> chunkSizes;
private final long bodySize;
private final byte[] body;
private final int sequenceNumber;
private final String sslProtocol;
public RecordedRequest(String requestLine, List<String> headers, List<Integer> chunkSizes,
long bodySize, byte[] body, int sequenceNumber, Socket socket) {
this.requestLine = requestLine;
this.headers = headers;
this.chunkSizes = chunkSizes;
this.bodySize = bodySize;
this.body = body;
this.sequenceNumber = sequenceNumber;
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
sslProtocol = sslSocket.getSession().getProtocol();
} else {
sslProtocol = null;
}
if (requestLine != null) {
int methodEnd = requestLine.indexOf(' ');
int pathEnd = requestLine.indexOf(' ', methodEnd + 1);
this.method = requestLine.substring(0, methodEnd);
this.path = requestLine.substring(methodEnd + 1, pathEnd);
} else {
this.method = null;
this.path = null;
}
}
public String getRequestLine() {
return requestLine;
}
public String getMethod() {
return method;
}
public String getPath() {
return path;
}
/**
* Returns all headers.
*/
public List<String> getHeaders() {
return headers;
}
/**
* Returns the first header named {@code name}, or null if no such header
* exists.
*/
public String getHeader(String name) {
name += ":";
for (String header : headers) {
if (name.regionMatches(true, 0, header, 0, name.length())) {
return header.substring(name.length()).trim();
}
}
return null;
}
/**
* Returns the headers named {@code name}.
*/
public List<String> getHeaders(String name) {
List<String> result = new ArrayList<String>();
name += ":";
for (String header : headers) {
if (name.regionMatches(true, 0, header, 0, name.length())) {
result.add(header.substring(name.length()).trim());
}
}
return result;
}
/**
* Returns the sizes of the chunks of this request's body, or an empty list
* if the request's body was empty or unchunked.
*/
public List<Integer> getChunkSizes() {
return chunkSizes;
}
/**
* Returns the total size of the body of this POST request (before
* truncation).
*/
public long getBodySize() {
return bodySize;
}
/**
* Returns the body of this POST request. This may be truncated.
*/
public byte[] getBody() {
return body;
}
/**
* Returns the body of this POST request decoded as a UTF-8 string.
*/
public String getUtf8Body() {
try {
return new String(body, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
}
/**
* Returns the index of this request on its HTTP connection. Since a single
* HTTP connection may serve multiple requests, each request is assigned its
* own sequence number.
*/
public int getSequenceNumber() {
return sequenceNumber;
}
/**
* Returns the connection's SSL protocol like {@code TLSv1}, {@code SSLv3},
* {@code NONE} or null if the connection doesn't use SSL.
*/
public String getSslProtocol() {
return sslProtocol;
}
@Override public String toString() {
return requestLine;
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (C) 2011 Google 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.google.mockwebserver;
/**
* What should be done with the incoming socket.
*/
public enum SocketPolicy {
/**
* Keep the socket open after the response. This is the default HTTP/1.1
* behavior.
*/
KEEP_OPEN,
/**
* Close the socket after the response. This is the default HTTP/1.0
* behavior.
*/
DISCONNECT_AT_END,
/**
* Wrap the socket with SSL at the completion of this request/response
* pair. Used for CONNECT messages to tunnel SSL over an HTTP proxy.
*/
UPGRADE_TO_SSL_AT_END,
/**
* Request immediate close of connection without even reading the
* request.
*
* <p>Use to simulate the real life case of losing connection
* because of bugger SSL server close connection when it seems
* something like a compression method or TLS extension it doesn't
* understand, instead of simply ignoring it like it should.
*/
DISCONNECT_AT_START,
/**
* Don't trust the client during the SSL handshake.
*/
FAIL_HANDSHAKE,
/**
* Shutdown the socket input after sending the response. For testing bad
* behavior.
*/
SHUTDOWN_INPUT_AT_END,
/**
* Shutdown the socket output after sending the response. For testing bad
* behavior.
*/
SHUTDOWN_OUTPUT_AT_END
}

View File

@@ -0,0 +1,100 @@
/*
* Copyright (C) 2012 Google 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.google.mockwebserver;
import junit.framework.TestCase;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class CustomDispatcherTest extends TestCase {
private MockWebServer mockWebServer = new MockWebServer();
@Override
public void tearDown() throws Exception {
mockWebServer.shutdown();
}
public void testSimpleDispatch() throws Exception {
mockWebServer.play();
final List<RecordedRequest> requestsMade = new ArrayList<RecordedRequest>();
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
requestsMade.add(request);
return new MockResponse();
}
};
assertEquals(0, requestsMade.size());
mockWebServer.setDispatcher(dispatcher);
final URL url = mockWebServer.getUrl("/");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.getResponseCode(); // Force the connection to hit the "server".
// Make sure our dispatcher got the request.
assertEquals(1, requestsMade.size());
}
public void testOutOfOrderResponses() throws Exception {
AtomicInteger firstResponseCode = new AtomicInteger();
AtomicInteger secondResponseCode = new AtomicInteger();
mockWebServer.play();
final String secondRequest = "/bar";
final String firstRequest = "/foo";
final CountDownLatch latch = new CountDownLatch(1);
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getPath().equals(firstRequest)) {
latch.await();
}
return new MockResponse();
}
};
mockWebServer.setDispatcher(dispatcher);
final Thread startsFirst = buildRequestThread(firstRequest, firstResponseCode);
startsFirst.start();
final Thread endsFirst = buildRequestThread(secondRequest, secondResponseCode);
endsFirst.start();
endsFirst.join();
assertEquals(0, firstResponseCode.get()); // First response is still waiting.
assertEquals(200, secondResponseCode.get()); // Second response is done.
latch.countDown();
startsFirst.join();
assertEquals(200, firstResponseCode.get()); // And now it's done!
assertEquals(200, secondResponseCode.get()); // (Still done).
}
private Thread buildRequestThread(final String path, final AtomicInteger responseCode) {
return new Thread(new Runnable() {
@Override public void run() {
final URL url = mockWebServer.getUrl(path);
final HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
responseCode.set(conn.getResponseCode()); // Force the connection to hit the "server".
} catch (IOException e) {
}
}
});
}
}

View File

@@ -0,0 +1,289 @@
/*
* Copyright (C) 2011 Google 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.google.mockwebserver;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import junit.framework.TestCase;
public final class MockWebServerTest extends TestCase {
private MockWebServer server = new MockWebServer();
@Override protected void tearDown() throws Exception {
server.shutdown();
super.tearDown();
}
public void testRecordedRequestAccessors() {
List<String> headers = Arrays.asList(
"User-Agent: okhttp",
"Cookie: s=square",
"Cookie: a=android",
"X-Whitespace: left",
"X-Whitespace:right ",
"X-Whitespace: both "
);
List<Integer> chunkSizes = Collections.emptyList();
byte[] body = {'A', 'B', 'C'};
String requestLine = "GET / HTTP/1.1";
RecordedRequest request = new RecordedRequest(
requestLine, headers, chunkSizes, body.length, body, 0, null);
assertEquals("s=square", request.getHeader("cookie"));
assertEquals(Arrays.asList("s=square", "a=android"), request.getHeaders("cookie"));
assertEquals("left", request.getHeader("x-whitespace"));
assertEquals(Arrays.asList("left", "right", "both"), request.getHeaders("x-whitespace"));
assertEquals("ABC", request.getUtf8Body());
}
public void testDefaultMockResponse() {
MockResponse response = new MockResponse();
assertEquals(Arrays.asList("Content-Length: 0"), response.getHeaders());
assertEquals("HTTP/1.1 200 OK", response.getStatus());
}
public void testSetBodyAdjustsHeaders() throws IOException {
MockResponse response = new MockResponse().setBody("ABC");
assertEquals(Arrays.asList("Content-Length: 3"), response.getHeaders());
InputStream in = response.getBodyStream();
assertEquals('A', in.read());
assertEquals('B', in.read());
assertEquals('C', in.read());
assertEquals(-1, in.read());
assertEquals("HTTP/1.1 200 OK", response.getStatus());
}
public void testMockResponseAddHeader() {
MockResponse response = new MockResponse()
.clearHeaders()
.addHeader("Cookie: s=square")
.addHeader("Cookie", "a=android");
assertEquals(Arrays.asList("Cookie: s=square", "Cookie: a=android"),
response.getHeaders());
}
public void testMockResponseSetHeader() {
MockResponse response = new MockResponse()
.clearHeaders()
.addHeader("Cookie: s=square")
.addHeader("Cookie: a=android")
.addHeader("Cookies: delicious");
response.setHeader("cookie", "r=robot");
assertEquals(Arrays.asList("Cookies: delicious", "cookie: r=robot"),
response.getHeaders());
}
/**
* Clients who adhere to <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3">100
* Status</a> expect the server to send an interim response with status code
* 100 before they send their payload.
*
* <h4>Note</h4>
*
* JRE 6 only passes this test if
* {@code -Dsun.net.http.allowRestrictedHeaders=true} is set.
*/
public void testExpect100ContinueWithBody() throws Exception {
server.enqueue(new MockResponse());
server.play();
URL url = server.getUrl("/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Expect", "100-continue");
connection.setDoOutput(true);
connection.getOutputStream().write("hello".getBytes());
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
assertEquals(server.getRequestCount(), 1);
RecordedRequest request = server.takeRequest();
assertEquals(request.getRequestLine(), "PUT / HTTP/1.1");
assertEquals("5", request.getHeader("Content-Length"));
assertEquals(5, request.getBodySize());
assertEquals("hello", new String(request.getBody()));
// below fails on JRE 6 unless -Dsun.net.http.allowRestrictedHeaders=true is set
assertEquals("100-continue", request.getHeader("Expect"));
}
public void testExpect100ContinueWithNoBody() throws Exception {
server.enqueue(new MockResponse());
server.play();
URL url = server.getUrl("/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Expect", "100-continue");
connection.setRequestProperty("Content-Length", "0");
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(0);
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
assertEquals(server.getRequestCount(), 1);
RecordedRequest request = server.takeRequest();
assertEquals(request.getRequestLine(), "PUT / HTTP/1.1");
assertEquals("0", request.getHeader("Content-Length"));
assertEquals(0, request.getBodySize());
// below fails on JRE 6 unless -Dsun.net.http.allowRestrictedHeaders=true is set
assertEquals("100-continue", request.getHeader("Expect"));
}
public void testRegularResponse() throws Exception {
server.enqueue(new MockResponse().setBody("hello world"));
server.play();
URL url = server.getUrl("/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Language", "en-US");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
assertEquals("hello world", reader.readLine());
RecordedRequest request = server.takeRequest();
assertEquals("GET / HTTP/1.1", request.getRequestLine());
assertTrue(request.getHeaders().contains("Accept-Language: en-US"));
}
public void testRedirect() throws Exception {
server.play();
server.enqueue(new MockResponse()
.setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
.addHeader("Location: " + server.getUrl("/new-path"))
.setBody("This page has moved!"));
server.enqueue(new MockResponse().setBody("This is the new location!"));
URLConnection connection = server.getUrl("/").openConnection();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("This is the new location!", reader.readLine());
RecordedRequest first = server.takeRequest();
assertEquals("GET / HTTP/1.1", first.getRequestLine());
RecordedRequest redirect = server.takeRequest();
assertEquals("GET /new-path HTTP/1.1", redirect.getRequestLine());
}
/**
* Test that MockWebServer blocks for a call to enqueue() if a request
* is made before a mock response is ready.
*/
public void testDispatchBlocksWaitingForEnqueue() throws Exception {
server.play();
new Thread() {
@Override public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
server.enqueue(new MockResponse().setBody("enqueued in the background"));
}
}.start();
URLConnection connection = server.getUrl("/").openConnection();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("enqueued in the background", reader.readLine());
}
public void testNonHexadecimalChunkSize() throws Exception {
server.enqueue(new MockResponse()
.setBody("G\r\nxxxxxxxxxxxxxxxx\r\n0\r\n\r\n")
.clearHeaders()
.addHeader("Transfer-encoding: chunked"));
server.play();
URLConnection connection = server.getUrl("/").openConnection();
InputStream in = connection.getInputStream();
try {
in.read();
fail();
} catch (IOException expected) {
}
}
public void testResponseTimeout() throws Exception {
server.enqueue(new MockResponse()
.setBody("ABC")
.clearHeaders()
.addHeader("Content-Length: 4"));
server.enqueue(new MockResponse()
.setBody("DEF"));
server.play();
URLConnection urlConnection = server.getUrl("/").openConnection();
urlConnection.setReadTimeout(1000);
InputStream in = urlConnection.getInputStream();
assertEquals('A', in.read());
assertEquals('B', in.read());
assertEquals('C', in.read());
try {
in.read(); // if Content-Length was accurate, this would return -1 immediately
fail();
} catch (SocketTimeoutException expected) {
}
URLConnection urlConnection2 = server.getUrl("/").openConnection();
InputStream in2 = urlConnection2.getInputStream();
assertEquals('D', in2.read());
assertEquals('E', in2.read());
assertEquals('F', in2.read());
assertEquals(-1, in2.read());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
}
public void testDisconnectAtStart() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
server.enqueue(new MockResponse()); // The jdk's HttpUrlConnection is a bastard.
server.enqueue(new MockResponse());
server.play();
try {
server.getUrl("/a").openConnection().getInputStream();
} catch (IOException e) {
// Expected.
}
server.getUrl("/b").openConnection().getInputStream(); // Should succeed.
}
public void testStreamingResponseBody() throws Exception {
InputStream responseBody = new ByteArrayInputStream("ABC".getBytes("UTF-8"));
server.enqueue(new MockResponse().setBody(responseBody, 3));
server.play();
InputStream in = server.getUrl("/").openConnection().getInputStream();
assertEquals('A', in.read());
assertEquals('B', in.read());
assertEquals('C', in.read());
assertEquals(-1, responseBody.read()); // The body is exhausted.
}
}