1 package com.github.javaparser.utils;
2 
3 import com.github.javaparser.*;
4 import com.github.javaparser.ast.expr.Expression;
5 import okhttp3.OkHttpClient;
6 import okhttp3.Request;
7 import okhttp3.Response;
8 
9 import java.io.*;
10 import java.net.URISyntaxException;
11 import java.net.URL;
12 import java.nio.file.Files;
13 import java.nio.file.Path;
14 import java.nio.file.Paths;
15 import java.util.*;
16 import java.util.stream.Collectors;
17 import java.util.zip.ZipEntry;
18 import java.util.zip.ZipInputStream;
19 
20 import static com.github.javaparser.ParserConfiguration.LanguageLevel.*;
21 import static com.github.javaparser.Providers.provider;
22 import static com.github.javaparser.utils.CodeGenerationUtils.f;
23 import static com.github.javaparser.utils.Utils.*;
24 import static java.nio.charset.StandardCharsets.*;
25 import static java.util.Arrays.*;
26 import static org.junit.jupiter.api.Assertions.*;
27 
28 public class TestUtils {
29     /**
30      * Takes care of setting all the end of line character to platform specific ones.
31      */
readResource(String resourceName)32     public static String readResource(String resourceName) throws IOException {
33         if (resourceName.startsWith("/")) {
34             resourceName = resourceName.substring(1);
35         }
36         try (final InputStream resourceAsStream = TestUtils.class.getClassLoader().getResourceAsStream(resourceName)) {
37             if (resourceAsStream == null) {
38                 fail("not found: " + resourceName);
39             }
40             try (final InputStreamReader reader = new InputStreamReader(resourceAsStream, UTF_8);
41                  final BufferedReader br = new BufferedReader(reader)) {
42                 final StringBuilder builder = new StringBuilder();
43                 String line;
44                 while ((line = br.readLine()) != null) {
45                     builder.append(line).append(EOL);
46                 }
47                 return builder.toString();
48             }
49         }
50     }
51 
readTextResource(Class<?> relativeClass, String resourceName)52     public static String readTextResource(Class<?> relativeClass, String resourceName) {
53         final URL resourceAsStream = relativeClass.getResource(resourceName);
54         try {
55             byte[] bytes = Files.readAllBytes(Paths.get(resourceAsStream.toURI()));
56             return new String(bytes, UTF_8);
57         } catch (IOException | URISyntaxException e) {
58             fail(e);
59             return null;
60         }
61     }
62 
assertInstanceOf(Class<?> expectedType, Object instance)63     public static void assertInstanceOf(Class<?> expectedType, Object instance) {
64         assertTrue(expectedType.isAssignableFrom(instance.getClass()), f("%s is not an instance of %s.", instance.getClass(), expectedType));
65     }
66 
67     /**
68      * Unzip a zip file into a directory.
69      */
unzip(Path zipFile, Path outputFolder)70     public static void unzip(Path zipFile, Path outputFolder) throws IOException {
71         Log.info("Unzipping %s to %s", () -> zipFile, () -> outputFolder);
72 
73         final byte[] buffer = new byte[1024 * 1024];
74 
75         outputFolder.toFile().mkdirs();
76 
77         try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile.toFile()))) {
78             ZipEntry ze = zis.getNextEntry();
79 
80             while (ze != null) {
81                 final Path newFile = outputFolder.resolve(ze.getName());
82 
83                 if (ze.isDirectory()) {
84                     Log.trace("mkdir %s", newFile::toAbsolutePath);
85                     newFile.toFile().mkdirs();
86                 } else {
87                     Log.info("unzip %s", newFile::toAbsolutePath);
88                     try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
89                         int len;
90                         while ((len = zis.read(buffer)) > 0) {
91                             fos.write(buffer, 0, len);
92                         }
93                     }
94                 }
95                 zis.closeEntry();
96                 ze = zis.getNextEntry();
97             }
98 
99         }
100         Log.info("Unzipped %s to %s", () -> zipFile, () -> outputFolder);
101     }
102 
103     /**
104      * Download a file from a URL to disk.
105      */
download(URL url, Path destination)106     public static void download(URL url, Path destination) throws IOException {
107         OkHttpClient client = new OkHttpClient();
108         Request request = new Request.Builder()
109                 .url(url)
110                 .build();
111 
112         Response response = client.newCall(request).execute();
113         Files.write(destination, response.body().bytes());
114     }
115 
temporaryDirectory()116     public static String temporaryDirectory() {
117         return System.getProperty("java.io.tmpdir");
118     }
119 
assertCollections(Collection<?> expected, Collection<?> actual)120     public static void assertCollections(Collection<?> expected, Collection<?> actual) {
121         final StringBuilder out = new StringBuilder();
122         for (Object e : expected) {
123             if (actual.contains(e)) {
124                 actual.remove(e);
125             } else {
126                 out.append("Missing: ").append(e).append(EOL);
127             }
128         }
129         for (Object a : actual) {
130             out.append("Unexpected: ").append(a).append(EOL);
131         }
132 
133         String s = out.toString();
134         if (s.isEmpty()) {
135             return;
136         }
137         fail(s);
138     }
139 
assertProblems(ParseResult<?> result, String... expectedArg)140     public static void assertProblems(ParseResult<?> result, String... expectedArg) {
141         assertProblems(result.getProblems(), expectedArg);
142     }
143 
assertProblems(List<Problem> result, String... expectedArg)144     public static void assertProblems(List<Problem> result, String... expectedArg) {
145         Set<String> actual = result.stream().map(Problem::toString).collect(Collectors.toSet());
146         Set<String> expected = new HashSet<>(asList(expectedArg));
147         assertCollections(expected, actual);
148     }
149 
assertNoProblems(ParseResult<?> result)150     public static void assertNoProblems(ParseResult<?> result) {
151         assertProblems(result);
152     }
153 
assertExpressionValid(String expression)154     public static void assertExpressionValid(String expression) {
155         JavaParser javaParser = new JavaParser(new ParserConfiguration().setLanguageLevel(JAVA_9));
156         ParseResult<Expression> result = javaParser.parse(ParseStart.EXPRESSION, provider(expression));
157         assertTrue(result.isSuccessful(), result.getProblems().toString());
158     }
159 
160     /**
161      * Assert that "actual" equals "expected", and that any EOL characters in "actual" are correct for the platform.
162      */
assertEqualsNoEol(String expected, String actual)163     public static void assertEqualsNoEol(String expected, String actual) {
164         assertEquals(normalizeEolInTextBlock(expected, EOL), actual);
165     }
166 }
167