View Javadoc

1   package com.atlassian.gzipfilter;
2   
3   import junit.framework.TestCase;
4   
5   import javax.servlet.ServletOutputStream;
6   import javax.servlet.http.HttpServletResponse;
7   import java.io.ByteArrayInputStream;
8   import java.io.ByteArrayOutputStream;
9   import java.io.IOException;
10  import java.util.zip.GZIPInputStream;
11  
12  import static org.hamcrest.MatcherAssert.assertThat;
13  import static org.hamcrest.core.IsEqual.equalTo;
14  import static org.mockito.Mockito.mock;
15  import static org.mockito.Mockito.when;
16  
17  public class TestGzipResponseWrapper extends TestCase
18  {
19      public void testCreateValidGzipStreamEvenWhenNothingWrittenToResponse() throws Exception
20      {
21          final HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);
22          final ByteArrayServletOutputStream byteOutputStream = new ByteArrayServletOutputStream();
23          when(mockHttpResponse.getOutputStream())
24                  .thenReturn(byteOutputStream);
25  
26          final GzipResponseWrapper gzipResponseWrapper = new GzipResponseWrapper(mockHttpResponse, "UTF-8");
27  
28          gzipResponseWrapper.finishResponse();
29  
30          //verify an empty but valid gzip stream was constructed
31          final byte[] content = byteOutputStream.getContent();
32          final GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(content));
33          assertThat(gzipInputStream.read(), equalTo(-1));
34      }
35  
36      static class ByteArrayServletOutputStream extends ServletOutputStream
37      {
38          private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
39  
40          @Override
41          public void write(final int b) throws IOException
42          {
43              outputStream.write(b);
44          }
45  
46          byte[] getContent()
47          {
48              return outputStream.toByteArray();
49          }
50      }
51  }