1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package libcore.java.util.zip;
18
19import junit.framework.TestCase;
20import java.io.ByteArrayOutputStream;
21import java.io.IOException;
22import java.io.InputStream;
23import java.io.OutputStream;
24import java.util.Arrays;
25import java.util.Random;
26import java.util.zip.GZIPOutputStream;
27
28public final class GZIPOutputStreamTest extends TestCase {
29  public void testShortMessage() throws IOException {
30    byte[] data = gzip(("Hello World").getBytes("UTF-8"));
31    assertEquals("[31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -13, 72, -51, -55, -55, 87, 8, -49, " +
32                 "47, -54, 73, 1, 0, 86, -79, 23, 74, 11, 0, 0, 0]", Arrays.toString(data));
33  }
34
35  public void testLongMessage() throws IOException {
36    byte[] data = new byte[1024 * 1024];
37    new Random().nextBytes(data);
38    assertTrue(Arrays.equals(data, GZIPInputStreamTest.gunzip(gzip(data))));
39  }
40
41  public static byte[] gzip(byte[] bytes) throws IOException {
42    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
43    OutputStream gzippedOut = new GZIPOutputStream(bytesOut);
44    gzippedOut.write(bytes);
45    gzippedOut.close();
46    return bytesOut.toByteArray();
47  }
48
49  public void testSyncFlushEnabled() throws Exception {
50    InputStream in = DeflaterOutputStreamTest.createInflaterStream(GZIPOutputStream.class, true);
51    assertEquals(1, in.read());
52    assertEquals(2, in.read());
53    assertEquals(3, in.read());
54    in.close();
55  }
56
57  public void testSyncFlushDisabled() throws Exception {
58    InputStream in = DeflaterOutputStreamTest.createInflaterStream(GZIPOutputStream.class, false);
59    try {
60      in.read();
61      fail();
62    } catch (IOException expected) {
63    }
64    in.close();
65  }
66
67  // https://code.google.com/p/android/issues/detail?id=62589
68  public void testFlushAfterFinish() throws Exception {
69    byte[] responseBytes = "Some data to gzip".getBytes();
70    ByteArrayOutputStream output = new ByteArrayOutputStream(responseBytes.length);
71    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(output, true);
72    gzipOutputStream.write(responseBytes);
73    gzipOutputStream.finish();
74    // Calling flush() after finish() shouldn't throw.
75    gzipOutputStream.flush();
76    gzipOutputStream.close();
77  }
78}
79