Skip to content

Commit

Permalink
Set all unit tests to use port 0 for both the HttpProxyServer and the…
Browse files Browse the repository at this point in the history
… Jetty web servers. Fixed failing IdleTest. Added TimeoutTest.
  • Loading branch information
jekh committed Mar 16, 2015
1 parent d68ddb8 commit 352628d
Show file tree
Hide file tree
Showing 18 changed files with 443 additions and 263 deletions.
17 changes: 15 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,24 @@

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
<artifactId>mockito-core</artifactId>
<version>2.0.5-beta</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<version>3.9.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
Expand Down
56 changes: 25 additions & 31 deletions src/test/java/org/littleshoot/proxy/AbstractProxyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,11 @@
public abstract class AbstractProxyTest {
protected static final String DEFAULT_RESOURCE = "/";

protected static final AtomicInteger WEB_SERVER_PORT_SEQ = new AtomicInteger(
50000);
protected static final AtomicInteger WEB_SERVER_HTTPS_PORT_SEQ = new AtomicInteger(
53000);
protected static final AtomicInteger PROXY_SERVER_PORT_SEQ = new AtomicInteger(
56000);

protected int webServerPort = 0;
protected int httpsWebServerPort = 0;
protected int proxyServerPort = 0;

protected HttpHost webHost = new HttpHost("127.0.0.1",
webServerPort);
protected HttpHost httpsWebHost = new HttpHost(
"127.0.0.1", httpsWebServerPort, "https");
protected int webServerPort = -1;
protected int httpsWebServerPort = -1;

protected HttpHost webHost;
protected HttpHost httpsWebHost;

/**
* The server used by the tests.
Expand Down Expand Up @@ -101,18 +91,22 @@ public void initializeCounters() {

@Before
public void runSetUp() throws Exception {
// Set up new ports for everything based on sequence numbers
webServerPort = WEB_SERVER_PORT_SEQ.getAndIncrement();
httpsWebServerPort = WEB_SERVER_HTTPS_PORT_SEQ.getAndIncrement();
proxyServerPort = PROXY_SERVER_PORT_SEQ.getAndIncrement();

webHost = new HttpHost("127.0.0.1",
webServerPort);
httpsWebHost = new HttpHost(
"127.0.0.1", httpsWebServerPort, "https");

webServer = TestUtils.startWebServer(webServerPort,
httpsWebServerPort);
webServer = TestUtils.startWebServer(true);

// find out what ports the HTTP and HTTPS connectors were bound to
httpsWebServerPort = TestUtils.findLocalHttpsPort(webServer);
if (httpsWebServerPort < 0) {
throw new RuntimeException("HTTPS connector should already be open and listening, but port was " + webServerPort);
}

webServerPort = TestUtils.findLocalHttpPort(webServer);
if (webServerPort < 0) {
throw new RuntimeException("HTTP connector should already be open and listening, but port was " + webServerPort);
}

webHost = new HttpHost("127.0.0.1", webServerPort);
httpsWebHost = new HttpHost("127.0.0.1", httpsWebServerPort, "https");

setUp();
}

Expand Down Expand Up @@ -171,14 +165,14 @@ protected ResponseInfo httpPostWithApacheClient(
try {
if (isProxied) {
final HttpHost proxy = new HttpHost("127.0.0.1",
proxyServerPort);
proxyServer.getListenAddress().getPort());
httpClient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
if (username != null && password != null) {
httpClient.getCredentialsProvider()
.setCredentials(
new AuthScope("127.0.0.1",
proxyServerPort),
proxyServer.getListenAddress().getPort()),
new UsernamePasswordCredentials(username,
password));
}
Expand Down Expand Up @@ -210,14 +204,14 @@ protected ResponseInfo httpGetWithApacheClient(HttpHost host,
DefaultHttpClient httpClient = buildHttpClient();
try {
if (isProxied) {
HttpHost proxy = new HttpHost("127.0.0.1", proxyServerPort);
HttpHost proxy = new HttpHost("127.0.0.1", proxyServer.getListenAddress().getPort());
httpClient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, proxy);
if (username != null && password != null) {
httpClient.getCredentialsProvider()
.setCredentials(
new AuthScope("127.0.0.1",
proxyServerPort),
proxyServer.getListenAddress().getPort()),
new UsernamePasswordCredentials(username,
password));
}
Expand Down
15 changes: 3 additions & 12 deletions src/test/java/org/littleshoot/proxy/BaseChainedProxyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@
* by the downstream proxy was received by the upstream proxy.
*/
public abstract class BaseChainedProxyTest extends BaseProxyTest {
protected static final AtomicInteger UPSTREAM_PROXY_SERVER_PORT_SEQ = new AtomicInteger(
59000);

private int upstreamProxyPort;

private final AtomicLong REQUESTS_SENT_BY_DOWNSTREAM = new AtomicLong(
0l);
private final AtomicLong REQUESTS_RECEIVED_BY_UPSTREAM = new AtomicLong(
Expand Down Expand Up @@ -52,25 +47,21 @@ public void requestReceivedFromClient(FlowContext flowContext,

@Override
protected void setUp() {
// Set up ports from sequence
upstreamProxyPort = UPSTREAM_PROXY_SERVER_PORT_SEQ
.getAndIncrement();

REQUESTS_SENT_BY_DOWNSTREAM.set(0);
REQUESTS_RECEIVED_BY_UPSTREAM.set(0);
TRANSPORTS_USED.clear();
this.upstreamProxy = upstreamProxy().start();
this.proxyServer = bootstrapProxy()
.withName("Downstream")
.withPort(proxyServerPort)
.withPort(0)
.withChainProxyManager(chainedProxyManager())
.plusActivityTracker(DOWNSTREAM_TRACKER).start();
}

protected HttpProxyServerBootstrap upstreamProxy() {
return DefaultHttpProxyServer.bootstrap()
.withName("Upstream")
.withPort(upstreamProxyPort)
.withPort(0)
.plusActivityTracker(UPSTREAM_TRACKER);
}

Expand Down Expand Up @@ -141,7 +132,7 @@ public InetSocketAddress getChainedProxyAddress() {
try {
return new InetSocketAddress(InetAddress
.getByName("127.0.0.1"),
upstreamProxyPort);
upstreamProxy.getListenAddress().getPort());
} catch (UnknownHostException uhe) {
throw new RuntimeException(
"Unable to resolve 127.0.0.1?!");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected void setUp() {
unableToConnect.set(false);
this.proxyServer = bootstrapProxy()
.withName("Downstream")
.withPort(proxyServerPort)
.withPort(0)
.withChainProxyManager(new ChainedProxyManager() {
@Override
public void lookupChainedProxies(HttpRequest httpRequest,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,11 @@

import static org.littleshoot.proxy.TransportProtocol.*;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.SSLEngine;

import org.littleshoot.proxy.extras.SelfSignedSslEngineSource;

public class EncryptedUDTChainedProxyTest extends BaseChainedProxyTest {
private static final AtomicInteger localPort = new AtomicInteger(61000);

private final SslEngineSource sslEngineSource = new SelfSignedSslEngineSource(
"chain_proxy_keystore_1.jks");

Expand Down Expand Up @@ -39,12 +34,6 @@ public boolean requiresEncryption() {
public SSLEngine newSslEngine() {
return sslEngineSource.newSslEngine();
}

@Override
public InetSocketAddress getLocalAddress() {
return new InetSocketAddress("127.0.0.1",
localPort.getAndIncrement());
}
};
}
}
99 changes: 65 additions & 34 deletions src/test/java/org/littleshoot/proxy/EndToEndStoppingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.matchers.Times;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
Expand All @@ -18,19 +22,38 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

/**
* End to end test making sure the proxy is able to service simple HTTP requests
* and stop at the end. Made into a unit test from isopov and nasis's
* contributions at: https://github.com/adamfisk/LittleProxy/issues/36
*/
public class EndToEndStoppingTest {
private static final Logger log = LoggerFactory.getLogger(EndToEndStoppingTest.class);

private final Logger log = LoggerFactory.getLogger(getClass());
private ClientAndServer mockServer;
private int mockServerPort;

@Before
public void setUp() {
// replace this with port 0 when MockServer supports it
mockServerPort = new Random().nextInt(55000) + 10000;
mockServer = new ClientAndServer(mockServerPort);
}

@After
public void tearDown() {
if (mockServer != null) {
mockServer.stop();
}
}

/**
* This is a quick test from nasis that exhibits different behavior from
Expand All @@ -40,14 +63,13 @@ public class EndToEndStoppingTest {
* properly tests.
*/
public static void main(final String[] args) throws Exception {
int port = 9090;
HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
.withPort(port)
.withPort(0)
.start();

Proxy proxy = new Proxy();
proxy.setProxyType(Proxy.ProxyType.MANUAL);
String proxyStr = String.format("localhost:%d", port);
String proxyStr = String.format("localhost:%d", proxyServer.getListenAddress().getPort());
proxy.setHttpProxy(proxyStr);
proxy.setSslProxy(proxyStr);

Expand All @@ -69,22 +91,25 @@ public static void main(final String[] args) throws Exception {

@Test
public void testWithHttpClient() throws Exception {
mockServer.when(request()
.withMethod("GET")
.withPath("/success"),
Times.exactly(1))
.respond(response()
.withStatusCode(200)
.withBody("Success!")
);
// final String url = "https://www.exceptional.io/api/errors?" +
// "api_key="+"9848f38fb5ad1db0784675b75b9152c87dc1eb95"+"&protocol_version=6";

final String url = "https://www.exceptional.io";
final String url = "http://127.0.0.1:" + mockServerPort + "/success";
final String[] sites = { url };// "https://www.google.com.ua"};//"https://exceptional.io"};//"http://www.google.com.ua"};
for (final String site : sites) {
runSiteTestWithHttpClient(site);
}
}

private void runSiteTestWithHttpClient(final String site) throws Exception {
final int PROXY_PORT = 9097;
final HttpClient client = TestUtils.createProxiedHttpClient(PROXY_PORT);

// final HttpPost get = new HttpPost(site);
final HttpGet get = new HttpGet(site);
// HttpResponse response = client.execute(get);

// assertEquals(200, response.getStatusLine().getStatusCode());
Expand All @@ -98,51 +123,57 @@ private void runSiteTestWithHttpClient(final String site) throws Exception {
* System.out.println("Request went through proxy"); } });
*/

final HttpProxyServer plain = DefaultHttpProxyServer.bootstrap()
.withPort(PROXY_PORT)
final HttpProxyServer proxy = DefaultHttpProxyServer.bootstrap()
.withPort(0)
.withFiltersSource(new HttpFiltersSourceAdapter() {
@Override
public HttpFilters filterRequest(HttpRequest originalRequest) {
return new HttpFiltersAdapter(originalRequest) {
@Override
public io.netty.handler.codec.http.HttpResponse proxyToServerRequest(
HttpObject httpObject) {
System.out
.println("Request with through proxy");
System.out.println("Request with through proxy");
return null;
}
};
}
}).start();
final HttpProxyServer proxy = plain;

// client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
// new HttpHost("75.101.134.244", PROXY_PORT));
// new HttpHost("localhost", PROXY_PORT, "https"));
HttpResponse response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode());
final HttpEntity entity = response.getEntity();
final String body =
IOUtils.toString(entity.getContent()).toLowerCase();
EntityUtils.consume(entity);

log.info("Consuming entity -- got body: {}", body);
EntityUtils.consume(response.getEntity());

log.info("Stopping proxy");
proxy.stop();

try {
final HttpClient client = TestUtils.createProxiedHttpClient(proxy.getListenAddress().getPort());

// final HttpPost get = new HttpPost(site);
final HttpGet get = new HttpGet(site);

// client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
// new HttpHost("75.101.134.244", PROXY_PORT));
// new HttpHost("localhost", PROXY_PORT, "https"));
HttpResponse response = client.execute(get);
assertEquals(200, response.getStatusLine().getStatusCode());
final HttpEntity entity = response.getEntity();
final String body = IOUtils.toString(entity.getContent());
EntityUtils.consume(entity);

log.info("Consuming entity -- got body: {}", body);
EntityUtils.consume(response.getEntity());

log.info("Stopping proxy");
} finally {
if (proxy != null) {
proxy.stop();
}
}
}

// @Test
public void testWithWebDriver() throws Exception {
int port = 9090;
HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
.withPort(port)
.withPort(0)
.start();

Proxy proxy = new Proxy();
proxy.setProxyType(Proxy.ProxyType.MANUAL);
String proxyStr = String.format("localhost:%d", port);
String proxyStr = String.format("localhost:%d", proxyServer.getListenAddress().getPort());
proxy.setHttpProxy(proxyStr);
proxy.setSslProxy(proxyStr);

Expand Down
Loading

0 comments on commit 352628d

Please sign in to comment.