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