1 package it.com.atlassian.gzipfilter;
2
3 import junit.framework.TestCase;
4 import org.apache.commons.httpclient.Header;
5 import org.apache.commons.httpclient.HttpClient;
6 import org.apache.commons.httpclient.HttpMethod;
7 import org.apache.commons.httpclient.methods.GetMethod;
8 import org.junit.Test;
9 import static org.junit.Assert.*;
10
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.util.zip.GZIPInputStream;
14
15
16
17
18 public class TestFlushing
19 {
20
21 @Test
22 public void testFlushingWithNoFilter() throws Exception {
23 doTimingTest(null, null);
24 }
25 @Test
26 public void testFlushingWithGzFilter() throws Exception {
27 doTimingTest(IntegrationTestUtils.GZIP_RESPONSE_HEADER, IntegrationTestUtils.GZIP_ACCEPT_HEADER);
28 }
29
30 private void doTimingTest(Header expectedContentEncodoing, Header acceptHeader) throws IOException {
31 long pause = 4000;
32 HttpClient client = new HttpClient();
33 HttpMethod method = new GetMethod(IntegrationTestUtils.URL + "flushing.html?delay=" + pause);
34 if (acceptHeader != null) {
35 method.addRequestHeader(acceptHeader);
36 }
37
38 long t0 = System.currentTimeMillis();
39 int rc = client.executeMethod(method);
40 long t1 = System.currentTimeMillis();
41 assertEquals("Should return 200 - success", 200, rc);
42 assertEquals(expectedContentEncodoing, method.getResponseHeader("Content-Encoding"));
43 InputStream response = method.getResponseBodyAsStream();
44 if (acceptHeader != null) {
45 response = new GZIPInputStream(response, 1);
46 }
47
48 expect("first", response);
49 long t2 = System.currentTimeMillis();
50 expect("second", response);
51 long t3 = System.currentTimeMillis();
52 expect("last", response);
53 long t4 = System.currentTimeMillis();
54
55 assertTrue("read 'first' in response took: " + (t2 - t0), (t2 - t0) < 100);
56 assertTimeWithin(pause, t2, t3);
57 assertTimeWithin(pause, t3, t4);
58 }
59
60 private static void assertTimeWithin(long expectedDelay, long t0, long t1) {
61 assertEquals(expectedDelay, t1 - t0, 80);
62 }
63
64 private static void expect(String expected, InputStream in) throws IOException {
65 for (int i = 0; i < expected.length(); i++) {
66 int a = expected.charAt(i);
67 int b = in.read();
68 assertEquals(a, b);
69 }
70 }
71 }