aboutsummaryrefslogtreecommitdiff
path: root/generator/src/test/java/com/google/archivepatcher/generator/PreDiffPlannerTest.java
blob: 38b4c6b098ea10a2471683fc594ad1777a6ed0ae (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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
// Copyright 2016 Google Inc. 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.archivepatcher.generator;

import com.google.archivepatcher.generator.DefaultDeflateCompressionDiviner.DivinationResult;
import com.google.archivepatcher.shared.DefaultDeflateCompatibilityWindow;
import com.google.archivepatcher.shared.JreDeflateParameters;
import com.google.archivepatcher.shared.RandomAccessFileInputStream;
import com.google.archivepatcher.shared.TypedRange;
import com.google.archivepatcher.shared.UnitTestZipArchive;
import com.google.archivepatcher.shared.UnitTestZipEntry;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link PreDiffPlanner}.
 */
@RunWith(JUnit4.class)
@SuppressWarnings("javadoc")
public class PreDiffPlannerTest {

  // All the A and B entries consist of a chunk of text followed by a standard corpus of text from
  // the DefaultDeflateCompatibilityDiviner that ensures the tests will be able to discriminate
  // between any compression level. Without this additional corpus text, multiple compression levels
  // can match the entry and the unit tests would not be accurate.
  private static final UnitTestZipEntry ENTRY_A_LEVEL_6 =
      UnitTestZipArchive.makeUnitTestZipEntry("/path A", 6, "entry A", null);
  private static final UnitTestZipEntry ENTRY_A_LEVEL_9 =
      UnitTestZipArchive.makeUnitTestZipEntry("/path A", 9, "entry A", null);
  private static final UnitTestZipEntry ENTRY_A_STORED =
      UnitTestZipArchive.makeUnitTestZipEntry("/path A", 0, "entry A", null);
  private static final UnitTestZipEntry ENTRY_B_LEVEL_6 =
      UnitTestZipArchive.makeUnitTestZipEntry("/path B", 6, "entry B", null);
  private static final UnitTestZipEntry ENTRY_B_LEVEL_9 =
      UnitTestZipArchive.makeUnitTestZipEntry("/path B", 9, "entry B", null);

  /**
   * Entry C1 is a small entry WITHOUT the standard corpus of text from
   * {@link DefaultDeflateCompatibilityWindow} appended. It has exactly the same compressed length
   * as {@link #FIXED_LENGTH_ENTRY_C2_LEVEL_6}, and can be used to test the byte-matching logic in
   * the code when the compressed lengths are identical.
   */
  private static final UnitTestZipEntry FIXED_LENGTH_ENTRY_C1_LEVEL_6 =
      new UnitTestZipEntry("/path C", 6, "qqqqqqqqqqqqqqqqqqqqqqqqqqqq", null);

  /**
   * Entry C2 is a small entry WITHOUT the standard corpus of text from
   * {@link DefaultDeflateCompatibilityWindow} appended. It has exactly the same compressed length
   * as {@link #FIXED_LENGTH_ENTRY_C1_LEVEL_6}, and can be used to test the byte-matching logic in
   * the code when the compressed lengths are identical.
   */
  private static final UnitTestZipEntry FIXED_LENGTH_ENTRY_C2_LEVEL_6 =
      new UnitTestZipEntry("/path C", 6, "rrrrrrrrrrrrrrrrrrrrrrrrrrrr", null);

  // The "shadow" entries are exact copies of ENTRY_A_* but have a different path. These are used
  // for the detection of renames that don't involve modification (i.e., the uncompressed CRC32 is
  // exactly the same as the ENTRY_A_* entries)
  private static final UnitTestZipEntry SHADOW_ENTRY_A_LEVEL_1 =
      UnitTestZipArchive.makeUnitTestZipEntry("/uncompressed data same as A", 1, "entry A", null);
  private static final UnitTestZipEntry SHADOW_ENTRY_A_LEVEL_6 =
      UnitTestZipArchive.makeUnitTestZipEntry("/same as A level 6", 6, "entry A", null);
  private static final UnitTestZipEntry SHADOW_ENTRY_A_LEVEL_9 =
      UnitTestZipArchive.makeUnitTestZipEntry("/same as A level 9", 9, "entry A", null);
  private static final UnitTestZipEntry SHADOW_ENTRY_A_STORED =
      UnitTestZipArchive.makeUnitTestZipEntry("/same as A stored", 0, "entry A", null);

  private List<File> tempFilesCreated;
  private Map<File, Map<ByteArrayHolder, MinimalZipEntry>> entriesByPathByTempFile;

  @Before
  public void setup() {
    tempFilesCreated = new LinkedList<File>();
    entriesByPathByTempFile = new HashMap<File, Map<ByteArrayHolder, MinimalZipEntry>>();
  }

  @After
  public void tearDown() {
    for (File file : tempFilesCreated) {
      try {
        file.delete();
      } catch (Exception ignored) {
        // Nothing
      }
    }
  }

  /**
   * Stores the specified bytes to disk in a temp file, returns the temp file and caches the zip
   * entries for the file for use in later code.
   * @param data the bytes to store, expected to be a valid zip file
   * @throws IOException if it fails
   */
  private File storeAndMapArchive(byte[] data) throws IOException {
    File file = File.createTempFile("pdpt", "zip");
    tempFilesCreated.add(file);
    file.deleteOnExit();
    FileOutputStream out = new FileOutputStream(file);
    out.write(data);
    out.flush();
    out.close();
    Map<ByteArrayHolder, MinimalZipEntry> entriesByPath = new HashMap<>();
    for (MinimalZipEntry zipEntry : MinimalZipArchive.listEntries(file)) {
      ByteArrayHolder key = new ByteArrayHolder(zipEntry.getFileNameBytes());
      entriesByPath.put(key, zipEntry);
    }
    entriesByPathByTempFile.put(file, entriesByPath);
    return file;
  }

  /**
   * Finds a unit test entry in the specified temp file.
   * @param tempFile the archive to search within
   * @param unitTestEntry the unit test entry to look up
   * @return the {@link MinimalZipEntry} corresponding to the unit test entry
   */
  private MinimalZipEntry findEntry(File tempFile, UnitTestZipEntry unitTestEntry) {
    Map<ByteArrayHolder, MinimalZipEntry> subMap = entriesByPathByTempFile.get(tempFile);
    Assert.assertNotNull("temp file not mapped", subMap);
    ByteArrayHolder key;
    try {
      key = new ByteArrayHolder(unitTestEntry.path.getBytes("UTF8"));
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }
    return subMap.get(key);
  }

  /**
   * Finds the {@link TypedRange} corresponding to the compressed data for the specified unit test
   * entry in the specified temp file.
   * @param tempFile the archive to search within
   * @param unitTestEntry the unit test entry to look up
   * @return the {@link TypedRange} for the unit test entry's compressed data
   */
  private TypedRange<Void> findRangeWithoutParams(File tempFile, UnitTestZipEntry unitTestEntry) {
    MinimalZipEntry found = findEntry(tempFile, unitTestEntry);
    Assert.assertNotNull("entry not found in temp file", found);
    return new TypedRange<Void>(
        found.getFileOffsetOfCompressedData(), found.getCompressedSize(), null);
  }

  /**
   * Finds the {@link TypedRange} corresponding to the compressed data for the specified unit test
   * entry in the specified temp file.
   * @param tempFile the archive to search within
   * @param unitTestEntry the unit test entry to look up
   * @return the {@link TypedRange} for the unit test entry's compressed data
   */
  private TypedRange<JreDeflateParameters> findRangeWithParams(
      File tempFile, UnitTestZipEntry unitTestEntry) {
    MinimalZipEntry found = findEntry(tempFile, unitTestEntry);
    Assert.assertNotNull("entry not found in temp file", found);
    return new TypedRange<JreDeflateParameters>(
        found.getFileOffsetOfCompressedData(),
        found.getCompressedSize(),
        JreDeflateParameters.of(unitTestEntry.level, 0, true));
  }

  /**
   * Deliberately introduce an error into the specified entry. This will make the entry impossible
   * to divine the settings for, because it is broken.
   * @param tempFile the archive to search within
   * @param unitTestEntry the unit test entry to deliberately corrupt
   */
  private void corruptEntryData(File tempFile, UnitTestZipEntry unitTestEntry) throws IOException {
    TypedRange<Void> range = findRangeWithoutParams(tempFile, unitTestEntry);
    Assert.assertTrue("range too short to corrupt with 'junk'", range.getLength() >= 4);
    try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw")) {
      raf.seek(range.getOffset());
      raf.write("junk".getBytes("UTF8"));
    }
  }

  /**
   * Deliberately garble the compression method in the specified entry such that it is no longer
   * deflate.
   * @param tempFile the archive to search within
   * @param unitTestEntry the unit test entry to deliberately corrupt
   */
  private void corruptCompressionMethod(File tempFile, UnitTestZipEntry unitTestEntry)
      throws IOException {
    long centralDirectoryRecordOffset = -1;
    try (RandomAccessFileInputStream rafis = new RandomAccessFileInputStream(tempFile)) {
      long startOfEocd = MinimalZipParser.locateStartOfEocd(rafis, 32768);
      rafis.setRange(startOfEocd, tempFile.length() - startOfEocd);
      MinimalCentralDirectoryMetadata centralDirectoryMetadata = MinimalZipParser.parseEocd(rafis);
      int numEntries = centralDirectoryMetadata.getNumEntriesInCentralDirectory();
      rafis.setRange(
          centralDirectoryMetadata.getOffsetOfCentralDirectory(),
          centralDirectoryMetadata.getLengthOfCentralDirectory());
      for (int x = 0; x < numEntries; x++) {
        long recordStartOffset = rafis.getPosition();
        MinimalZipEntry candidate = MinimalZipParser.parseCentralDirectoryEntry(rafis);
        if (candidate.getFileName().equals(unitTestEntry.path)) {
          // Located! Track offset and bail out.
          centralDirectoryRecordOffset = recordStartOffset;
          x = numEntries;
        }
      }
    }

    Assert.assertNotEquals("Entry not found", -1L, centralDirectoryRecordOffset);
    try (RandomAccessFile raf = new RandomAccessFile(tempFile, "rw")) {
      // compression method is a 2 byte field stored 10 bytes into the record
      raf.seek(centralDirectoryRecordOffset + 10);
      raf.write(7);
      raf.write(7);
    }
  }

  private PreDiffPlan invokeGeneratePreDiffPlan(
      File oldFile, File newFile, RecommendationModifier... recommendationModifiers)
      throws IOException {
    Map<ByteArrayHolder, MinimalZipEntry> originalOldArchiveZipEntriesByPath =
        new LinkedHashMap<ByteArrayHolder, MinimalZipEntry>();
    Map<ByteArrayHolder, MinimalZipEntry> originalNewArchiveZipEntriesByPath =
        new LinkedHashMap<ByteArrayHolder, MinimalZipEntry>();
    Map<ByteArrayHolder, JreDeflateParameters> originalNewArchiveJreDeflateParametersByPath =
        new LinkedHashMap<ByteArrayHolder, JreDeflateParameters>();

    for (MinimalZipEntry zipEntry : MinimalZipArchive.listEntries(oldFile)) {
      ByteArrayHolder key = new ByteArrayHolder(zipEntry.getFileNameBytes());
      originalOldArchiveZipEntriesByPath.put(key, zipEntry);
    }

    DefaultDeflateCompressionDiviner diviner = new DefaultDeflateCompressionDiviner();
    for (DivinationResult divinationResult : diviner.divineDeflateParameters(newFile)) {
      ByteArrayHolder key = new ByteArrayHolder(divinationResult.minimalZipEntry.getFileNameBytes());
      originalNewArchiveZipEntriesByPath.put(key, divinationResult.minimalZipEntry);
      originalNewArchiveJreDeflateParametersByPath.put(key, divinationResult.divinedParameters);
    }

    PreDiffPlanner preDiffPlanner =
        new PreDiffPlanner(
            oldFile,
            originalOldArchiveZipEntriesByPath,
            newFile,
            originalNewArchiveZipEntriesByPath,
            originalNewArchiveJreDeflateParametersByPath,
            recommendationModifiers);
    return preDiffPlanner.generatePreDiffPlan();
  }

  private void checkRecommendation(PreDiffPlan plan, QualifiedRecommendation... expected) {
    Assert.assertNotNull(plan.getQualifiedRecommendations());
    Assert.assertEquals(expected.length, plan.getQualifiedRecommendations().size());
    for (int x = 0; x < expected.length; x++) {
      QualifiedRecommendation actual = plan.getQualifiedRecommendations().get(x);
      Assert.assertEquals(
          expected[x].getOldEntry().getFileName(), actual.getOldEntry().getFileName());
      Assert.assertEquals(
          expected[x].getNewEntry().getFileName(), actual.getNewEntry().getFileName());
      Assert.assertEquals(expected[x].getRecommendation(), actual.getRecommendation());
      Assert.assertEquals(expected[x].getReason(), actual.getReason());
    }
  }

  @Test
  public void testGeneratePreDiffPlan_OneCompressedEntry_Unchanged() throws IOException {
    byte[] bytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    File oldFile = storeAndMapArchive(bytes);
    File newFile = storeAndMapArchive(bytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to leave the entry alone in both the old and new archives (empty plans).
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_LEVEL_6),
        findEntry(newFile, ENTRY_A_LEVEL_6),
        Recommendation.UNCOMPRESS_NEITHER,
        RecommendationReason.COMPRESSED_BYTES_IDENTICAL));
  }

  @Test
  public void testGeneratePreDiffPlan_OneCompressedEntry_LengthsChanged() throws IOException {
    // Test detection of compressed entry differences based on length mismatch.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress the entry in both the old and new archives.
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertEquals(1, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithParams(newFile, ENTRY_A_LEVEL_9), plan.getNewFileUncompressionPlan().get(0));
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_LEVEL_6),
        findEntry(newFile, ENTRY_A_LEVEL_9),
        Recommendation.UNCOMPRESS_BOTH,
        RecommendationReason.COMPRESSED_BYTES_CHANGED));
  }

  @Test
  public void testGeneratePreDiffPlan_OneCompressedEntry_BytesChanged() throws IOException {
    // Test detection of compressed entry differences based on binary content mismatch where the
    // compressed lengths are exactly the same - i.e., force a byte-by-byte comparison of the
    // compressed data in the two entries.
    byte[] oldBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(FIXED_LENGTH_ENTRY_C1_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(FIXED_LENGTH_ENTRY_C2_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress the entry in both the old and new archives.
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(1, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, FIXED_LENGTH_ENTRY_C1_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertEquals(
        findRangeWithParams(newFile, FIXED_LENGTH_ENTRY_C2_LEVEL_6),
        plan.getNewFileUncompressionPlan().get(0));
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, FIXED_LENGTH_ENTRY_C1_LEVEL_6),
        findEntry(newFile, FIXED_LENGTH_ENTRY_C2_LEVEL_6),
        Recommendation.UNCOMPRESS_BOTH,
        RecommendationReason.COMPRESSED_BYTES_CHANGED));
  }

  @Test
  public void testGeneratePreDiffPlan_OneUncompressedEntry() throws IOException {
    // Test with uncompressed old and new. It doesn't matter whether the bytes are changed or
    // unchanged in this case.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing because both entries are already uncompressed
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_STORED),
        findEntry(newFile, ENTRY_A_STORED),
        Recommendation.UNCOMPRESS_NEITHER,
        RecommendationReason.BOTH_ENTRIES_UNCOMPRESSED));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_CompressedToUncompressed() throws IOException {
    // Test the migration of an entry from compressed (old archive) to uncompressed (new archive).
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_9));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress the entry in the old archive and do nothing in the new
    // archive (empty plan)
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_9),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_LEVEL_9),
        findEntry(newFile, ENTRY_A_STORED),
        Recommendation.UNCOMPRESS_OLD,
        RecommendationReason.COMPRESSED_CHANGED_TO_UNCOMPRESSED));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_UncompressedToCompressed() throws IOException {
    // Test the migration of an entry from uncompressed (old archive) to compressed (new archive).
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing in the old archive (empty plan) and uncompress the entry in
    // the new archive
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertEquals(1, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithParams(newFile, ENTRY_A_LEVEL_6), plan.getNewFileUncompressionPlan().get(0));
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_STORED),
        findEntry(newFile, ENTRY_A_LEVEL_6),
        Recommendation.UNCOMPRESS_NEW,
        RecommendationReason.UNCOMPRESSED_CHANGED_TO_COMPRESSED));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_UncompressedToUndivinable() throws IOException {
    // Test the migration of an entry from uncompressed (old archive) to compressed (new archive),
    // but make the new entry un-divinable and therefore un-recompressible.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    // Deliberately break the entry in the new file so that it will not be divinable
    corruptEntryData(newFile, ENTRY_A_LEVEL_6);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan WOULD be to do nothing in the old archive (empty plan) and uncompress the entry in
    // the new archive, but because the new entry is un-divinable it cannot be recompressed and so
    // the plan for the new archive should be empty as well.
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_STORED),
            findEntry(newFile, ENTRY_A_LEVEL_6),
            Recommendation.UNCOMPRESS_NEITHER,
            RecommendationReason.DEFLATE_UNSUITABLE));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_OldUncompressed_NewNonDeflate() throws IOException {
    // Test the case where the entry is compressed with something other than deflate in the new
    // archive; it is thus not reproducible, not divinable, and therefore cannot be uncompressed.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    corruptCompressionMethod(newFile, ENTRY_A_LEVEL_9);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing (empty plans) because the the entry in the old archive is
    // already uncompressed and the entry in the new archive is not compressed with deflate (i.e.,
    // cannot be recompressed so cannot be touched).
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_STORED),
        findEntry(newFile, ENTRY_A_LEVEL_9),
        Recommendation.UNCOMPRESS_NEITHER,
        RecommendationReason.UNSUITABLE));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_OldNonDeflate_NewUncompressed() throws IOException {
    // Test the case where the entry is compressed with something other than deflate in the old
    // archive; it can't be uncompressed, so there's no point in modifying the new entry either.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_9));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    corruptCompressionMethod(oldFile, ENTRY_A_LEVEL_9);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing (empty plans) because the the entry in the old archive is
    // not compressed with deflate, so there is no point in trying to do anything at all.
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_LEVEL_9),
        findEntry(newFile, ENTRY_A_STORED),
        Recommendation.UNCOMPRESS_NEITHER,
        RecommendationReason.UNSUITABLE));
  }

  @Test
  public void testGeneratePreDiffPlan_OneEntry_BothNonDeflate() throws IOException {
    // Test the case where the entry is compressed with something other than deflate; it is thus
    // not reproducible, not divinable, and therefore cannot be uncompressed.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    corruptCompressionMethod(oldFile, ENTRY_A_LEVEL_6);
    corruptCompressionMethod(newFile, ENTRY_A_LEVEL_9);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing (empty plans) because the entries are not compressed with
    // deflate
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(plan, new QualifiedRecommendation(
        findEntry(oldFile, ENTRY_A_LEVEL_6),
        findEntry(newFile, ENTRY_A_LEVEL_9),
        Recommendation.UNCOMPRESS_NEITHER,
        RecommendationReason.UNSUITABLE));
  }

  @Test
  public void testGeneratePreDiffPlan_TwoDifferentEntries_DifferentPaths() throws IOException {
    // Test the case where file paths are different as well as content within those files, i.e. each
    // entry is exclusive to its archive and is not the same
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_B_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing (empty plans) because entry A is only in the old archive and
    // entry B is only in the new archive, so there is nothing to diff.
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getQualifiedRecommendations().isEmpty());
  }

  @Test
  public void testGeneratePreDiffPlan_TwoEntriesEachArchive_SwappingOrder() throws IOException {
    // Test the case where two entries in each archive have both changed, AND they have changed
    // places in the file. The plan is supposed to be in file order, so that streaming is possible;
    // check that it is so.
    byte[] oldBytes =
        UnitTestZipArchive.makeTestZip(Arrays.asList(ENTRY_A_LEVEL_6, ENTRY_B_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Arrays.asList(ENTRY_B_LEVEL_9, ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress both entries, but the order is important. File order should
    // be in both plans.
    Assert.assertEquals(2, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(2, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_B_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(1));
    Assert.assertEquals(
        findRangeWithParams(newFile, ENTRY_B_LEVEL_9), plan.getNewFileUncompressionPlan().get(0));
    Assert.assertEquals(
        findRangeWithParams(newFile, ENTRY_A_LEVEL_9), plan.getNewFileUncompressionPlan().get(1));
  }

  @Test
  public void testGeneratePreDiffPlan_SimpleRename_Unchanged() throws IOException {
    // Test the case where file paths are different but the uncompressed content is the same.
    // The compression method used for both entries is identical, as are the compressed bytes.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(SHADOW_ENTRY_A_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to do nothing (empty plans) because the bytes are identical in both files
    // so the entries should remain compressed. However, unlike the case where there was no match,
    // there is now a qualified recommendation in the returned list.
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_LEVEL_6),
            findEntry(newFile, SHADOW_ENTRY_A_LEVEL_6),
            Recommendation.UNCOMPRESS_NEITHER,
            RecommendationReason.COMPRESSED_BYTES_IDENTICAL));
  }

  @Test
  public void testGeneratePreDiffPlan_SimpleRename_CompressionLevelChanged() throws IOException {
    // Test the case where file paths are different but the uncompressed content is the same.
    // The compression method used for each entry is different but the CRC32 is still the same, so
    // unlike like the plan with identical entries this time the plan should be to uncompress both
    // entries, allowing a super-efficient delta.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(SHADOW_ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress both entries so that a super-efficient delta can be done.
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertEquals(1, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithParams(newFile, SHADOW_ENTRY_A_LEVEL_9),
        plan.getNewFileUncompressionPlan().get(0));
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_LEVEL_6),
            findEntry(newFile, SHADOW_ENTRY_A_LEVEL_9),
            Recommendation.UNCOMPRESS_BOTH,
            RecommendationReason.COMPRESSED_BYTES_CHANGED));
  }

  @Test
  public void testGeneratePreDiffPlan_ClonedAndCompressionLevelChanged() throws IOException {
    // Test the case where an entry exists in both old and new APK with identical uncompressed
    // content but different compressed content ***AND*** additionally a new copy exists in the new
    // archive, also with identical uncompressed content and different compressed content, i.e.:
    //
    // OLD APK:                                NEW APK:
    // ------------------------------------    -----------------------------------------------
    // foo.xml (compressed level 6)            foo.xml (compressed level 9, content unchanged)
    //                                         bar.xml (copy of foo.xml, compressed level 1)
    //
    // This test ensures that in such cases the foo.xml from the old apk is only enqueued for
    // uncompression ONE TIME.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(
            Arrays.asList(SHADOW_ENTRY_A_LEVEL_1, SHADOW_ENTRY_A_LEVEL_9));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress both entries so that a super-efficient delta can be done.
    // Critically there should only be ONE command for the old file uncompression step!
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertEquals(2, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithParams(newFile, SHADOW_ENTRY_A_LEVEL_1),
        plan.getNewFileUncompressionPlan().get(0));
    Assert.assertEquals(
        findRangeWithParams(newFile, SHADOW_ENTRY_A_LEVEL_9),
        plan.getNewFileUncompressionPlan().get(1));
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_LEVEL_6),
            findEntry(newFile, SHADOW_ENTRY_A_LEVEL_1),
            Recommendation.UNCOMPRESS_BOTH,
            RecommendationReason.COMPRESSED_BYTES_CHANGED),
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_LEVEL_6),
            findEntry(newFile, SHADOW_ENTRY_A_LEVEL_9),
            Recommendation.UNCOMPRESS_BOTH,
            RecommendationReason.COMPRESSED_BYTES_CHANGED));
  }

  @Test
  public void testGeneratePreDiffPlan_SimpleRename_CompressedToUncompressed() throws IOException {
    // Test the case where file paths are different but the uncompressed content is the same.
    // The compression method is changed from compressed to uncompressed but the rename should still
    // be detected and the plan should be to uncompress the old entry only.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_LEVEL_6));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(SHADOW_ENTRY_A_STORED));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress the old entry so that a super-efficient delta can be done.
    // The new entry isn't touched because it is already uncompressed.
    Assert.assertEquals(1, plan.getOldFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithoutParams(oldFile, ENTRY_A_LEVEL_6),
        plan.getOldFileUncompressionPlan().get(0));
    Assert.assertTrue(plan.getNewFileUncompressionPlan().isEmpty());
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_LEVEL_6),
            findEntry(newFile, SHADOW_ENTRY_A_STORED),
            Recommendation.UNCOMPRESS_OLD,
            RecommendationReason.COMPRESSED_CHANGED_TO_UNCOMPRESSED));
  }

  @Test
  public void testGeneratePreDiffPlan_SimpleRename_UncompressedToCompressed() throws IOException {
    // Test the case where file paths are different but the uncompressed content is the same.
    // The compression method is changed from uncompressed to compressed but the rename should still
    // be detected and the plan should be to uncompress the new entry only.
    byte[] oldBytes = UnitTestZipArchive.makeTestZip(Collections.singletonList(ENTRY_A_STORED));
    byte[] newBytes =
        UnitTestZipArchive.makeTestZip(Collections.singletonList(SHADOW_ENTRY_A_LEVEL_6));
    File oldFile = storeAndMapArchive(oldBytes);
    File newFile = storeAndMapArchive(newBytes);
    PreDiffPlan plan = invokeGeneratePreDiffPlan(oldFile, newFile);
    Assert.assertNotNull(plan);
    // The plan should be to uncompress the new entry so that a super-efficient delta can be done.
    // The old entry isn't touched because it is already uncompressed.
    Assert.assertTrue(plan.getOldFileUncompressionPlan().isEmpty());
    Assert.assertEquals(1, plan.getNewFileUncompressionPlan().size());
    Assert.assertEquals(
        findRangeWithParams(newFile, SHADOW_ENTRY_A_LEVEL_6),
        plan.getNewFileUncompressionPlan().get(0));
    checkRecommendation(
        plan,
        new QualifiedRecommendation(
            findEntry(oldFile, ENTRY_A_STORED),
            findEntry(newFile, SHADOW_ENTRY_A_LEVEL_6),
            Recommendation.UNCOMPRESS_NEW,
            RecommendationReason.UNCOMPRESSED_CHANGED_TO_COMPRESSED));
  }

}