Skip to content

Commit

Permalink
When we want a port, take it.
Browse files Browse the repository at this point in the history
  • Loading branch information
squarejesse committed Apr 27, 2014
1 parent c7c1d26 commit da7ef58
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@
*/
package com.squareup.okhttp.mockwebserver.rule;

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 java.io.IOException;
import java.net.ServerSocket;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand All @@ -35,12 +33,14 @@
public class MockWebServerRule extends ExternalResource {
private static final Logger logger = Logger.getLogger(MockWebServerRule.class.getName());

private final int port = pickPort();
private final MockWebServer server = new MockWebServer();
private boolean started;

@Override protected void before() {
if (started) return;
started = true;
try {
server.play(port);
server.play();
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand All @@ -55,7 +55,8 @@ public class MockWebServerRule extends ExternalResource {
}

public int getPort() {
return port;
if (!started) before();
return server.getPort();
}

public int getRequestCount() {
Expand All @@ -78,16 +79,4 @@ public URL getUrl(String path) {
public MockWebServer get() {
return server;
}

private static int pickPort() {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
return socket.getLocalPort();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
Util.closeQuietly(socket);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,8 @@ public class MockWebServerRuleTest {
server.after();
}

@Test public void whenRuleCreatedPortIsAvailableAndServerNotYetPlayed() throws IOException {
@Test public void whenRuleCreatedPortIsAvailable() throws IOException {
assertTrue(server.getPort() > 0);

try {
server.get().getPort();
fail();
} catch (IllegalStateException e) {

}

// Verify the port is available.
new ServerSocket(server.getPort()).close();
}

@Test public void differentRulesGetDifferentPorts() throws IOException {
Expand Down

0 comments on commit da7ef58

Please sign in to comment.