aboutsummaryrefslogtreecommitdiff
path: root/core/src/test/java/fi/iki/elonen/integration/ShutdownTest.java
blob: 0fcb2751eb36d229fd1e8c766fcdd7aac82de28c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package fi.iki.elonen.integration;

import static org.junit.Assert.*;
import fi.iki.elonen.NanoHTTPD;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ShutdownTest {

    @Test
    public void connectionsAreClosedWhenServerStops() throws IOException {
        TestServer server = new TestServer();
        server.start();
        makeRequest();
        server.stop();
        try {
            makeRequest();
            fail("Connection should be closed!");
        } catch (IOException e) {
            // Expected exception
        }
    }

    private void makeRequest() throws MalformedURLException, IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8092/").openConnection();
        // Keep-alive seems to be on by default, but just in case that changes.
        connection.addRequestProperty("Connection", "keep-alive");
        InputStream in = connection.getInputStream();
        while (in.available() > 0) {
            in.read();
        }
        in.close();
    }

    private class TestServer extends NanoHTTPD {

        public TestServer() {
            super(8092);
        }

        @Override
        public Response serve(IHTTPSession session) {
            return new Response("Whatever");
        }
    }

}