1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.dependency.analyzer;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.nio.charset.StandardCharsets;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.util.HashSet;
28 import java.util.Set;
29 import java.util.jar.JarOutputStream;
30 import java.util.zip.ZipEntry;
31 import java.util.zip.ZipException;
32
33 import org.junit.jupiter.api.BeforeEach;
34 import org.junit.jupiter.api.Test;
35 import org.junit.jupiter.api.io.TempDir;
36
37 import static org.assertj.core.api.Assertions.assertThat;
38 import static org.assertj.core.api.Assertions.fail;
39
40
41
42
43
44
45
46 class DefaultClassAnalyzerTest {
47
48 @TempDir
49 private Path tempDir;
50
51 private Path file;
52
53 @BeforeEach
54 void setUp() throws IOException {
55 file = Files.createTempFile(tempDir, "test", ".jar");
56 try (JarOutputStream out = new JarOutputStream(new FileOutputStream(file.toFile()))) {
57 addZipEntry(out, "a/b/c.class", "class a.b.c");
58 addZipEntry(out, "x/y/z.class", "class x.y.z");
59 }
60 }
61
62 @Test
63 void testAnalyzeWithJar() throws IOException {
64 Set<String> expectedClasses = new HashSet<>();
65 expectedClasses.add("a.b.c");
66 expectedClasses.add("x.y.z");
67
68 DefaultClassAnalyzer analyzer = new DefaultClassAnalyzer();
69 Set<String> actualClasses = analyzer.analyze(file.toUri().toURL());
70
71 assertThat(actualClasses).isEqualTo(expectedClasses);
72 }
73
74 @Test
75 void testAnalyzeBadJar() throws IOException {
76
77
78 ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
79 Files.copy(file, baos);
80 byte[] ba = baos.toByteArray();
81 ba[50] = 1;
82 Files.write(file, ba);
83
84 ClassAnalyzer analyzer = new DefaultClassAnalyzer();
85
86 try {
87 analyzer.analyze(file.toUri().toURL());
88 fail("Exception expected");
89 } catch (ZipException e) {
90 assertThat(e).hasMessageStartingWith("Cannot process Jar entry on URL:");
91 }
92 }
93
94 private void addZipEntry(JarOutputStream out, String fileName, String content) throws IOException {
95 out.putNextEntry(new ZipEntry(fileName));
96 byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
97 out.write(bytes, 0, bytes.length);
98 }
99 }