Skip to content

Commit

Permalink
Use a real HTTP server in tests for the HTTP client
Browse files Browse the repository at this point in the history
If we open a socket and just close it, the client could not consider
it a server at all and won't throw a NoHttpResponseException.
  • Loading branch information
arteam committed Sep 15, 2017
1 parent ba9e9c0 commit 21fab93
Showing 1 changed file with 8 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricRegistryListener;
import com.codahale.metrics.Timer;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
Expand Down Expand Up @@ -52,21 +51,14 @@ public void registersExpectedMetricsGivenNameStrategy() throws Exception {

@Test
public void registersExpectedExceptionMetrics() throws Exception {
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("localhost", 0));
final HttpGet get = new HttpGet("http://localhost:" + server.getLocalPort() + "/");
HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);

final HttpGet get = new HttpGet("http://localhost:" + httpServer.getAddress().getPort() + "/");
final String requestMetricName = "request";
final String exceptionMetricName = "exception";

Thread serverThread = new Thread(() -> {
try {
final Socket socket = server.accept();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
});
serverThread.start();
httpServer.createContext("/", HttpExchange::close);
httpServer.start();

when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class)))
.thenReturn(requestMetricName);
Expand All @@ -79,8 +71,7 @@ public void registersExpectedExceptionMetrics() throws Exception {
} catch (NoHttpResponseException expected) {
assertThat(metricRegistry.getMeters()).containsKey("exception");
} finally {
serverThread.interrupt();
serverThread.join();
httpServer.stop(0);
}
}
}

0 comments on commit 21fab93

Please sign in to comment.