Skip to content

Commit

Permalink
GH-14 Failed to read input stream
Browse files Browse the repository at this point in the history
Fix bug in directory creation logic and split the nested try-catch statements into separate ones for more granular error messages.

Fixes #14
  • Loading branch information
anderseknert committed Jun 10, 2020
1 parent 5d4341b commit ec32094
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 40 deletions.
46 changes: 27 additions & 19 deletions src/main/java/com/bisnode/opa/TestRegoTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -50,37 +51,44 @@ public void testRego() {
List<String> command = Arrays.asList(location, "test", "--format=json", src, testSrc);

Process process;
int exitCode;
try {
logger.debug("Running command {}", String.join(" ", command));
process = new ProcessBuilder()
.directory(project.getRootDir())
.command(command)
.start();

int exitCode = process.waitFor();
exitCode = process.waitFor();

try (BufferedReader reader = bufferedInputReader(process.getInputStream())) {
String output = reader.lines().collect(Collectors.joining("\n"));
Document document = OpaToJunitConverter.fromOpaTestJson(output);
} catch (IOException | InterruptedException e) {
throw new TestExecutionException("Failed to start OPA process for tests", e);
}

String targetReport = getProject().getBuildDir().getAbsolutePath() + "/test-results/opa/";
if (!new File(targetReport).mkdirs()) {
throw new IOException("Could not create test results directory " + targetReport);
}
String output;
try (BufferedReader reader = bufferedInputReader(process.getInputStream())) {
output = reader.lines().collect(Collectors.joining("\n"));
} catch (IOException e) {
throw new TestExecutionException("Failed to read input stream from OPA process");
}

try (OutputStream out = new FileOutputStream(targetReport + "TEST-opa-tests.xml")) {
OpaToJunitConverter.write(document, out);
}
String targetReport = getProject().getBuildDir().getAbsolutePath() + "/test-results/opa/";
File tagetReportDir = new File(targetReport);
if (!tagetReportDir.exists() && !tagetReportDir.mkdirs()) {
throw new TestExecutionException("Could not create test results directory " + targetReport);
}

if (exitCode != 0) {
throw new TestExecutionException(output);
}
} catch (IOException e) {
throw new TestExecutionException("Failed to read input stream", e);
}
Document document = OpaToJunitConverter.fromOpaTestJson(output);
try (OutputStream out = new FileOutputStream(targetReport + "TEST-opa-tests.xml")) {
OpaToJunitConverter.write(document, out);
} catch (FileNotFoundException e) {
throw new TestExecutionException("");
} catch (IOException e) {
throw new TestExecutionException("Failed ");
}

} catch (IOException | InterruptedException e) {
throw new TestExecutionException("Failed to start OPA process for tests", e);
if (exitCode != 0) {
throw new TestExecutionException(output);
}
}

Expand Down
75 changes: 54 additions & 21 deletions src/testFunctional/java/com/bisnode/test/PluginFunctionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

@SuppressWarnings({"DuplicatedCode"})
@SuppressWarnings("DuplicatedCode")
public class PluginFunctionalTest {

@TempDir
Expand All @@ -60,17 +60,50 @@ public void testRunningSuccessfulTestProducesJUnitXMLOutput() throws IOException
Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego"));
Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), path.resolve("policy_test.rego"));

String buildFileContent = "opa {\n" +
" srcDir '" + directory + "'\n" +
" testDir '" + directory + "'\n" +
"}";
Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND);
Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND);

BuildResult result = prepareRunner(new StringWriter(), "testRego").build();
@Nullable BuildTask task = result.task(":testRego");

assertNotNull(task);
assertEquals(task.getOutcome(), TaskOutcome.SUCCESS);
assertEquals(TaskOutcome.SUCCESS, task.getOutcome());
assertNotNull(path.toFile());
assertNotNull(path.toFile().listFiles());

Path testResultPath = path.resolve("build/test-results/opa");
assertNotNull(testResultPath.toFile());
assertTrue(testResultPath.toFile().exists());

Path opaJunitXMLReportPath = testResultPath.resolve("TEST-opa-tests.xml");
assertNotNull(opaJunitXMLReportPath.toFile());
assertTrue(opaJunitXMLReportPath.toFile().exists());

Document document = readXmlDocument(opaJunitXMLReportPath.toFile());

Function<String, String> attributes = attributeRetriever(document);

assertEquals("1", attributes.apply("tests"));
assertEquals("0", attributes.apply("errors"));
assertEquals("0", attributes.apply("failures"));
}

@Test
public void testRunningTestWithExistingReportsDirectoryWorks() throws IOException {
String directory = tmpDir.getAbsolutePath();

Path path = Paths.get(directory);
Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego"));
Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), path.resolve("policy_test.rego"));

Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND);

Files.createDirectories(buildFile.toPath().getParent().resolve("build/test-results/opa"));

BuildResult result = prepareRunner(new StringWriter(), "testRego").build();
@Nullable BuildTask task = result.task(":testRego");

assertNotNull(task);
assertEquals(TaskOutcome.SUCCESS, task.getOutcome());
assertNotNull(path.toFile());
assertNotNull(path.toFile().listFiles());

Expand Down Expand Up @@ -99,17 +132,13 @@ public void testRunningFailingTestProducesJUnitXMLOutput() throws IOException {
Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), path.resolve("policy.rego"));
Files.copy(new ByteArrayInputStream(getRegoPolicyTestFail().getBytes(UTF_8)), path.resolve("policy_test.rego"));

String buildFileContent = "opa {\n" +
" srcDir '" + directory + "'\n" +
" testDir '" + directory + "'\n" +
"}";
Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND);
Files.write(buildFile.toPath(), getOpaBlockConfig(directory).getBytes(UTF_8), StandardOpenOption.APPEND);

BuildResult result = prepareRunner(new StringWriter(), "testRego").buildAndFail();
@Nullable BuildTask task = result.task(":testRego");

assertNotNull(task);
assertEquals(task.getOutcome(), TaskOutcome.FAILED);
assertEquals(TaskOutcome.FAILED, task.getOutcome());
assertNotNull(path.toFile());
assertNotNull(path.toFile().listFiles());

Expand Down Expand Up @@ -141,13 +170,10 @@ public void testProvidingTaskPropertiesOverridesDefaults() throws IOException {
Files.copy(new ByteArrayInputStream(getRegoPolicy().getBytes(UTF_8)), policyDirPath.resolve("policy.rego"));
Files.copy(new ByteArrayInputStream(getRegoPolicyTest().getBytes(UTF_8)), policyDirPath.resolve("policy_test.rego"));

String buildFileContent = "opa {\n" +
" srcDir '/tmp'\n" +
" testDir '/tmp'\n" +
"}\n\n" +
String buildFileContent = getOpaBlockConfig("/tmp") + "\n\n" +
"testRego {\n" +
" srcDir '" + policyDirPath.toAbsolutePath().toString() + "'\n" +
" testDir '" + policyDirPath.toAbsolutePath().toString() + "'\n" +
" srcDir '" + policyDirPath.toAbsolutePath() + "'\n" +
" testDir '" + policyDirPath.toAbsolutePath() + "'\n" +
"}";

Files.write(buildFile.toPath(), buildFileContent.getBytes(UTF_8), StandardOpenOption.APPEND);
Expand All @@ -156,7 +182,7 @@ public void testProvidingTaskPropertiesOverridesDefaults() throws IOException {
@Nullable BuildTask task = result.task(":testRego");

assertNotNull(task);
assertEquals(task.getOutcome(), TaskOutcome.SUCCESS);
assertEquals(TaskOutcome.SUCCESS, task.getOutcome());
assertNotNull(path.toFile());
assertNotNull(path.toFile().listFiles());

Expand Down Expand Up @@ -190,7 +216,7 @@ public void testRunningTestRegoCoverageTaskWithoutArgumentsWork() throws IOExcep
@Nullable BuildTask task = result.task(":testRegoCoverage");

assertNotNull(task);
assertEquals(Objects.requireNonNull(task).getOutcome(), TaskOutcome.SUCCESS);
assertEquals(TaskOutcome.SUCCESS, Objects.requireNonNull(task).getOutcome());
}

private GradleRunner prepareRunner(StringWriter writer, String... tasks) {
Expand All @@ -202,6 +228,13 @@ private GradleRunner prepareRunner(StringWriter writer, String... tasks) {
.withArguments(tasks);
}

private static String getOpaBlockConfig(String directory) {
return "opa {\n" +
" srcDir '" + directory + "'\n" +
" testDir '" + directory + "'\n" +
"}";
}

private static Document readXmlDocument(File file) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
Expand Down

0 comments on commit ec32094

Please sign in to comment.