aboutsummaryrefslogtreecommitdiff
path: root/core/src/test/java/fi/iki/elonen/HttpChunkedResponseTest.java
blob: c3fb1f0667cda469f170bd5e1591061a93ad45ef (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
54
55
56
57
58
59
package fi.iki.elonen;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;

import static fi.iki.elonen.NanoHTTPD.Response.Status.OK;

public class HttpChunkedResponseTest extends HttpServerTest {
    @org.junit.Test
    public void thatChunkedContentIsChunked() throws Exception {
        PipedInputStream pipedInputStream = new ChunkedInputStream(new String[]{
                "some",
                "thing which is longer than sixteen characters",
                "whee!",
                ""
        });
        String[] expected = {
                "HTTP/1.1 200 OK",
                "Content-Type: what/ever",
                "Date: .*",
                "Connection: keep-alive",
                "Transfer-Encoding: chunked",
                "",
                "4",
                "some",
                "2d",
                "thing which is longer than sixteen characters",
                "5",
                "whee!",
                "0",
                ""
        };
        testServer.response = new NanoHTTPD.Response(OK, "what/ever", pipedInputStream);
        testServer.response.setChunkedTransfer(true);

        ByteArrayOutputStream byteArrayOutputStream = invokeServer("GET / HTTP/1.0");

        assertResponse(byteArrayOutputStream, expected);
    }

    private static class ChunkedInputStream extends PipedInputStream {
        int chunk = 0;
        String[] chunks;

        private ChunkedInputStream(String[] chunks) {
            this.chunks = chunks;
        }

        @Override
        public synchronized int read(byte[] buffer) throws IOException {
            // Too implementation-linked, but...
            for (int i = 0; i < chunks[chunk].length(); ++i) {
                buffer[i] = (byte) chunks[chunk].charAt(i);
            }
            return chunks[chunk++].length();
        }
    }
}