aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/singlejar/javatests/com/google/devtools/build/singlejar/FakeZipFile.java
blob: cdddd0d0e7059394dc25324837397011b3a1e257 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.singlejar;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import com.google.devtools.build.singlejar.SingleJarTest.EntryMode;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * A fake zip file to assert that a given {@link ZipInputStream} contains
 * specified entries in a specified order. Just for unit testing.
 */
public final class FakeZipFile {

  /**
   * Validates an input provided as a byte array.
   */
  public static interface ByteValidator {
    /**
     * Check if {@code object} is the expected input. If {@code object} does not match the expected
     * pattern, an assertion should fails with the necessary message.
     */
    void validate(byte[] object);
  }

  private static void assertSameByteArray(byte[] expected, byte[] actual) {
    if (expected == null) {
      assertNull(actual);
    } else {
      assertArrayEquals(expected, actual);
    }
  }

  private static byte[] readZipEntryContent(ZipInputStream zipInput) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesCopied;
    while ((bytesCopied = zipInput.read(buffer)) != -1) {
      out.write(buffer, 0, bytesCopied);
    }
    return out.toByteArray();
  }

  private static final class PlainByteValidator implements ByteValidator {
    private final byte[] expected;

    private PlainByteValidator(String expected) {
      this.expected = expected == null ? new byte[0] : expected.getBytes(UTF_8);
    }

    @Override
    public void validate(byte[] object) {
      assertSameByteArray(expected, object);
    }

  }

  private static final class FakeZipEntry {

    private final String name;
    private final ByteValidator content;
    private final Date date;
    private final byte[] extra;
    private final EntryMode mode;

    private FakeZipEntry(String name, Date date, String content, byte[] extra, EntryMode mode) {
      this.name = name;
      this.date = date;
      this.content = new PlainByteValidator(content);
      this.extra = extra;
      this.mode = mode;
    }

    private FakeZipEntry(String name, Date date, ByteValidator content, byte[] extra,
        EntryMode mode) {
      this.name = name;
      this.date = date;
      this.content = content;
      this.extra = extra;
      this.mode = mode;
    }

    public void assertNext(ZipInputStream zipInput) throws IOException {
      ZipEntry zipEntry = zipInput.getNextEntry();
      assertNotNull(zipEntry);
      switch (mode) {
        case EXPECT_DEFLATE:
          assertEquals(ZipEntry.DEFLATED, zipEntry.getMethod());
          break;
        case EXPECT_STORED:
          assertEquals(ZipEntry.STORED, zipEntry.getMethod());
          break;
        default:
          // we don't care.
          break;
      }
      assertEquals(name, zipEntry.getName());
      if (date != null) {
        assertEquals(date.getTime(), zipEntry.getTime());
      }
      assertSameByteArray(extra, zipEntry.getExtra());
      content.validate(readZipEntryContent(zipInput));
    }
  }

  private final List<FakeZipEntry> entries = new ArrayList<>();

  public FakeZipFile addEntry(String name, String content) {
    entries.add(new FakeZipEntry(name, null, content, null, EntryMode.DONT_CARE));
    return this;
  }

  public FakeZipFile addEntry(String name, String content, boolean compressed) {
    entries.add(new FakeZipEntry(name, null, content, null,
        compressed ? EntryMode.EXPECT_DEFLATE : EntryMode.EXPECT_STORED));
    return this;
  }

  public FakeZipFile addEntry(String name, Date date, String content) {
    entries.add(new FakeZipEntry(name, date, content, null, EntryMode.DONT_CARE));
    return this;
  }

  public FakeZipFile addEntry(String name, Date date, String content, boolean compressed) {
    entries.add(new FakeZipEntry(name, date, content, null,
        compressed ? EntryMode.EXPECT_DEFLATE : EntryMode.EXPECT_STORED));
    return this;
  }

  public FakeZipFile addEntry(String name, ByteValidator content) {
    entries.add(new FakeZipEntry(name, null, content, null, EntryMode.DONT_CARE));
    return this;
  }

  public FakeZipFile addEntry(String name, ByteValidator content, boolean compressed) {
    entries.add(new FakeZipEntry(name, null, content, null,
        compressed ? EntryMode.EXPECT_DEFLATE : EntryMode.EXPECT_STORED));
    return this;
  }

  public FakeZipFile addEntry(String name, Date date, ByteValidator content) {
    entries.add(new FakeZipEntry(name, date, content, null, EntryMode.DONT_CARE));
    return this;
  }

  public FakeZipFile addEntry(String name, Date date, ByteValidator content,
      boolean compressed) {
    entries.add(new FakeZipEntry(name, date, content, null,
        compressed ? EntryMode.EXPECT_DEFLATE : EntryMode.EXPECT_STORED));
    return this;
  }

  public FakeZipFile addEntry(String name, byte[] extra) {
    entries.add(new FakeZipEntry(name, null, (String) null, extra, EntryMode.DONT_CARE));
    return this;
  }

  public FakeZipFile addEntry(String name, byte[] extra, boolean compressed) {
    entries.add(new FakeZipEntry(name, null, (String) null, extra,
        compressed ? EntryMode.EXPECT_DEFLATE : EntryMode.EXPECT_STORED));
    return this;
  }

  private byte[] preamble = null;

  public FakeZipFile addPreamble(byte[] contents) {
    preamble = Arrays.copyOf(contents, contents.length);
    return this;
  }

  private int getUnsignedShort(byte[] source, int offset) {
    int a = source[offset + 0] & 0xff;
    int b = source[offset + 1] & 0xff;
    return (b << 8) | a;
  }

  public void assertSame(byte[] data) throws IOException {
    int offset = 0;
    int length = data.length;
    if (preamble != null) {
      offset += preamble.length;
      length -= offset;
      byte[] maybePreamble = Arrays.copyOfRange(data, 0, offset);
      assertTrue(Arrays.equals(preamble, maybePreamble));
    }
    ZipInputStream zipInput = new ZipInputStream(new ByteArrayInputStream(data, offset, length));
    for (FakeZipEntry entry : entries) {
      entry.assertNext(zipInput);
    }
    assertNull(zipInput.getNextEntry());
    // Verify that the end of central directory data is correct.
    // This assumes that the end of directory is at the end of input and that there is no zip file
    // comment.
    int count = getUnsignedShort(data, data.length-14);
    assertEquals(entries.size(), count);
    count = getUnsignedShort(data, data.length-12);
    assertEquals(entries.size(), count);
  }

  /**
   * Assert that {@code expected} is the same zip file as {@code actual}. It is similar to
   * {@link org.junit.Assert#assertArrayEquals(byte[], byte[])} but should use a more
   * helpful error message.
   */
  public static void assertSame(byte[] expected, byte[] actual) throws IOException {
    // First parse the zip files, then compare to have explicit comparison messages.
    ZipInputStream expectedZip = new ZipInputStream(new ByteArrayInputStream(expected));
    ZipInputStream actualZip = new ZipInputStream(new ByteArrayInputStream(actual));
    StringBuffer actualFileList = new StringBuffer();
    StringBuffer expectedFileList = new StringBuffer();
    Map<String, ZipEntry> actualEntries = new HashMap<String, ZipEntry>();
    Map<String, ZipEntry> expectedEntries = new HashMap<String, ZipEntry>();
    Map<String, byte[]> actualEntryContents = new HashMap<String, byte[]>();
    Map<String, byte[]> expectedEntryContents = new HashMap<String, byte[]>();
    parseZipEntry(expectedZip, expectedFileList, expectedEntries, expectedEntryContents);
    parseZipEntry(actualZip, actualFileList, actualEntries, actualEntryContents);
    // Compare the ordered file list first.
    assertEquals(expectedFileList.toString(), actualFileList.toString());

    // Then compare each entry.
    for (String name : expectedEntries.keySet()) {
      ZipEntry expectedEntry = expectedEntries.get(name);
      ZipEntry actualEntry = actualEntries.get(name);
      assertEquals("Time differs for " + name, expectedEntry.getTime(), actualEntry.getTime());
      assertArrayEquals("Extraneous content differs for " + name,
          expectedEntry.getExtra(), actualEntry.getExtra());
      assertArrayEquals("Content differs for " + name,
          expectedEntryContents.get(name), actualEntryContents.get(name));
    }

    // Finally do a binary array comparison to be sure that test fails if files are different in
    // some way we don't test.
    assertArrayEquals(expected, actual);
  }

  private static void parseZipEntry(ZipInputStream expectedZip, StringBuffer expectedFileList,
      Map<String, ZipEntry> expectedEntries, Map<String, byte[]> expectedEntryContents)
      throws IOException {
    ZipEntry expectedEntry;
    while ((expectedEntry = expectedZip.getNextEntry()) != null) {
      expectedFileList.append(expectedEntry.getName()).append("\n");
      expectedEntries.put(expectedEntry.getName(), expectedEntry);
      expectedEntryContents.put(expectedEntry.getName(), readZipEntryContent(expectedZip));
    }
  }
}