summaryrefslogtreecommitdiff
path: root/src/test/java/org/zwobble/hobgoblin/compiler/ExampleTests.java
blob: 1c77a832480462b4cd0ffb1b5283ee458e6ed856 (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
package org.zwobble.hobgoblin.compiler;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.zwobble.hobgoblin.compiler.testing.TestProcessRunner;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.zwobble.precisely.AssertThat.assertThat;
import static org.zwobble.precisely.Matchers.equalTo;

public class ExampleTests {
    @TestFactory
    public Stream<DynamicTest> tests() {
        return ExampleSet.exampleSets()
            .map(exampleSet -> DynamicTest.dynamicTest(
                exampleSet.name(),
                () -> runTest(exampleSet)
            ));
    }

    private void runTest(ExampleSet exampleSet) throws IOException, InterruptedException, NoSuchAlgorithmException {
        HobgoblinCompiler.compile(exampleSet.path());

        var javaOutputPath = verifyJavaOutput(exampleSet);
        var rustOutputPath = verifyRustOutput(exampleSet);

        // TODO: make detection more robust
        if (exampleSet.name().contains("transient-0")) {
            var transient0OutputDirs = Stream.of(javaOutputPath, rustOutputPath)
                .map(outputPath -> outputPath.orElseThrow().resolve("transient-0"))
                .toList();

            var names = transient0OutputDirs.stream()
                .flatMap(outputPath -> Arrays.stream(outputPath.toFile().listFiles()).map(file -> file.getName()))
                .collect(Collectors.toSet())
                .stream()
                .sorted()
                .toList();

            for (var name : names) {
                var expectedBytes = Optional.<byte[]>empty();
                for (var transient0OutputDir : transient0OutputDirs) {
                    var actualBytes = Files.readAllBytes(transient0OutputDir.resolve(name));
                    if (expectedBytes.isEmpty()) {
                        expectedBytes = Optional.of(actualBytes);
                    } else {
                        assertThat(Arrays.equals(actualBytes, expectedBytes.get()), equalTo(true));
                    }
                }
            }
        }
    }

    private Optional<Path> verifyJavaOutput(ExampleSet exampleSet) throws NoSuchAlgorithmException, IOException, InterruptedException {
        return verifyOutput(exampleSet, "java", List.of("mvn", "test"));
    }

    private Optional<Path> verifyRustOutput(ExampleSet exampleSet) throws NoSuchAlgorithmException, IOException, InterruptedException {
        return verifyOutput(exampleSet, "rust", List.of("cargo", "test"));
    }

    private Optional<Path> verifyOutput(
        ExampleSet exampleSet,
        String name,
        List<String> command
    ) throws NoSuchAlgorithmException, IOException, InterruptedException {
        var outputPath = exampleSet.path().resolve("output").resolve(name);

        if (!outputPath.toFile().exists()) {
            return Optional.empty();
        }

        var currentHash = hashJavaProject(outputPath);

        var lastTestRunPath = outputPath.resolve("last-test-run.properties");
        var lastTestRun = readLastTestRun(lastTestRunPath);

        if (lastTestRun.isPresent() && lastTestRun.get().pass && lastTestRun.get().hash.equals(currentHash)) {
            return Optional.of(outputPath);
        }

        try {
            TestProcessRunner.command(command)
                .cwd(outputPath)
                .addEnvVar("HOBGOBLIN_OUTPUT_DIR", outputPath.toAbsolutePath().toString())
                .runCaptureOutput()
                .throwOnError();
            writeLastTestRun(lastTestRunPath, new LastTestRun(currentHash, true));
        } catch (Throwable exception) {
            writeLastTestRun(lastTestRunPath, new LastTestRun(currentHash, false));
            throw exception;
        }

        return Optional.of(outputPath);
    }

    private record LastTestRun(String hash, boolean pass) {}

    private Optional<LastTestRun> readLastTestRun(Path path) throws IOException {
        var properties = new Properties();
        try (var reader = Files.newBufferedReader(path)) {
            properties.load(reader);
            var hash = properties.getProperty("hash");
            var pass = properties.getProperty("result").equals("PASS");
            return Optional.of(new LastTestRun(hash, pass));
        } catch (NoSuchFileException exception) {
            return Optional.empty();
        }
    }

    private void writeLastTestRun(Path path, LastTestRun lastTestRun) throws IOException {
        var properties = new Properties();
        properties.setProperty("hash", lastTestRun.hash);
        properties.setProperty("result", lastTestRun.pass ? "PASS" : "FAIL");
        try (var writer = Files.newBufferedWriter(path)) {
            properties.store(writer, null);
        }
    }

    private String hashJavaProject(Path javaProjectPath) throws NoSuchAlgorithmException, IOException {
        var paths = collectJavaProjectSourcePaths(javaProjectPath);

        var digest = MessageDigest.getInstance("sha256");

        for (var path : paths) {
            digest.update(path.toString().getBytes(StandardCharsets.UTF_8));
            digest.update(new byte[]{0});
            var contents = Files.readAllBytes(path);
            digest.update(contents);
            digest.update(new byte[]{0});
        }

        return bytesToHex(digest.digest());
    }

    private static String bytesToHex(byte[] bytes) {
        var hexString = new StringBuilder(2 * bytes.length);
        for (var b : bytes) {
            var hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    private static List<Path> collectJavaProjectSourcePaths(Path javaProjectPath) throws IOException {
        var paths = new ArrayList<Path>();

        Files.walkFileTree(
            javaProjectPath, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(
                Path file,
                BasicFileAttributes attrs
            ) {
                if (!javaProjectPath.relativize(file).toString().equals("last-test-run.properties")) {
                    paths.add(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (javaProjectPath.relativize(dir).startsWith("target")) {
                    return FileVisitResult.SKIP_SUBTREE;
                } else {
                    return FileVisitResult.CONTINUE;
                }
            }
        });

        paths.sort(Comparator.naturalOrder());

        return paths;
    }
}