1package fi.iki.elonen;
2
3import java.io.ByteArrayOutputStream;
4import java.io.IOException;
5import java.io.PipedInputStream;
6
7import static fi.iki.elonen.NanoHTTPD.Response.Status.OK;
8
9public class HttpChunkedResponseTest extends HttpServerTest {
10    @org.junit.Test
11    public void thatChunkedContentIsChunked() throws Exception {
12        PipedInputStream pipedInputStream = new ChunkedInputStream(new String[]{
13                "some",
14                "thing which is longer than sixteen characters",
15                "whee!",
16                ""
17        });
18        String[] expected = {
19                "HTTP/1.1 200 OK",
20                "Content-Type: what/ever",
21                "Date: .*",
22                "Connection: keep-alive",
23                "Transfer-Encoding: chunked",
24                "",
25                "4",
26                "some",
27                "2d",
28                "thing which is longer than sixteen characters",
29                "5",
30                "whee!",
31                "0",
32                ""
33        };
34        testServer.response = new NanoHTTPD.Response(OK, "what/ever", pipedInputStream);
35        testServer.response.setChunkedTransfer(true);
36
37        ByteArrayOutputStream byteArrayOutputStream = invokeServer("GET / HTTP/1.0");
38
39        assertResponse(byteArrayOutputStream, expected);
40    }
41
42    private static class ChunkedInputStream extends PipedInputStream {
43        int chunk = 0;
44        String[] chunks;
45
46        private ChunkedInputStream(String[] chunks) {
47            this.chunks = chunks;
48        }
49
50        @Override
51        public synchronized int read(byte[] buffer) throws IOException {
52            // Too implementation-linked, but...
53            for (int i = 0; i < chunks[chunk].length(); ++i) {
54                buffer[i] = (byte) chunks[chunk].charAt(i);
55            }
56            return chunks[chunk++].length();
57        }
58    }
59}
60