private void assertResponsesWithHttpCode(RequestBuilder requestBuilder, int code) throws IOException { String requestBody = requestBuilder.toString(); Socket socket = getSocket(); OutputStream out = socket.getOutputStream(); out.write(requestBody.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; int numberOfLinesRead = 0; while ((line = in.readLine()) != null) { if (++numberOfLinesRead == 1) { assertThat(line, startsWith("HTTP/1.1 " + code)); break; } } if (numberOfLinesRead == 0) { fail("No server response was read"); } try { socket.close(); } catch (IOException e) { } }
@Test(expected = IOException.class) public void shouldCloseSocketAfterCloseConnectionRequest() throws IOException, InterruptedException { String requestBody = RequestBuilder.defaultBuilder() .get("/example/Index") .withHost(HOST + ":" + PORT) .withCloseConnection() .toString(); OutputStream out = null; try { Socket socket = getSocket(); out = socket.getOutputStream(); out.write(requestBody.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (in.readLine() != null) { // Simulate reading } } catch (IOException e) { fail("The test failed too early due IOException" + e.getMessage()); } int i = 0; while (i++ < 10) { // The following code will cause error on a closed socket Thread.sleep(100); out.write("X" .getBytes()); out.flush(); } }
@Test public void shouldHangSilentlyOnClosingSocket() throws IOException { String requestBody = RequestBuilder.defaultBuilder() .get("/43524938257493852435/SOMEUNKNOWNURL.html") .withCloseConnection() .toString(); Socket socket = getSocket(); OutputStream out = socket.getOutputStream(); out.write(requestBody.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; int numberOfLinesRead = 0; while ((line = in.readLine()) != null) { if (++numberOfLinesRead == 1) { assertThat(line, startsWith("HTTP/1.1 404")); socket.close(); break; } } if (numberOfLinesRead == 0) { fail("No server response was read"); } }