Skip to content

Commit

Permalink
WIP 314 Increase test coverage on mojo
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Ruhroth committed Dec 19, 2024
1 parent 490ede5 commit 1aa4133
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class Configuration {
@Builder.Default
Boolean consoleReport = false;
@Builder.Default
Boolean failOnErrors = false;
Boolean failOnErrors = true;
@Builder.Default
Integer httpConnectionTimeout = 5000;
@Getter(AccessLevel.NONE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,16 @@ public class HtmlSanityCheckMojo extends AbstractMojo {
@Parameter
private List<Class<? extends Checker>> checkerClasses = AllCheckers.CHECKER_CLASSES;

static PerRunResults performChekcs(Configuration myConfig) throws MojoExecutionException {
try {
AllChecksRunner allChecksRunner = new AllChecksRunner(myConfig);
PerRunResults allChecks = allChecksRunner.performAllChecks();
return allChecks;
} catch (IOException e) {
throw new MojoExecutionException(e);
}
}

// tag::maven-plugin-implementation[]
public void execute() throws MojoExecutionException {
logBuildParameter();
Expand All @@ -193,42 +203,46 @@ public void execute() throws MojoExecutionException {
// Check if configuration is valid
try {
myConfig.validate();
// Create output directories
checkingResultsDir.mkdirs();
if (!checkingResultsDir.isDirectory() || !checkingResultsDir.canWrite()) {
throw new MojoExecutionException("Cannot write to checking results directory.");
}
if (junitResultsDir != null) {
junitResultsDir.mkdirs();
if (!junitResultsDir.isDirectory() || !junitResultsDir.canWrite()) {
throw new MojoExecutionException("Cannot write to JUnit results directory.");
}
}

// Perform checks
AllChecksRunner allChecksRunner = new AllChecksRunner(myConfig);
PerRunResults allChecks = allChecksRunner.performAllChecks();

// Handle findings
int nrOfFindingsOnAllPages = allChecks.nrOfFindingsOnAllPages();
getLog().debug("Found " + nrOfFindingsOnAllPages + " error(s) on all checked pages");

if (failOnErrors && nrOfFindingsOnAllPages > 0) {
String failureMsg = String.format(
"Your build configuration included 'failOnErrors=true', and %d error(s) were found on all checked pages. See %s for a detailed report.",
nrOfFindingsOnAllPages, checkingResultsDir
);
throw new MojoExecutionException(failureMsg);
}
} catch (MisconfigurationException e) {
throw new MojoExecutionException(e);
} catch (IOException e) {
throw new MojoExecutionException(e);
}

// Create output directories
createoutputDirs(myConfig.getCheckingResultsDir(), "Cannot write to checking results directory.");
if (myConfig.getJunitResultsDir() != null) {
createoutputDirs(myConfig.getJunitResultsDir(), "Cannot write to JUnit results directory.");
}

// Perform checks
PerRunResults allChecks = performChekcs(myConfig);

// Handle findings
handleFindings(allChecks.nrOfFindingsOnAllPages(), myConfig);

}

void handleFindings(int nrOfFindingsOnAllPages, Configuration config) throws MojoExecutionException {
getLog().debug("Found " + nrOfFindingsOnAllPages + " error(s) on all checked pages");

if (config.getFailOnErrors() && nrOfFindingsOnAllPages > 0) {
String failureMsg = String.format(
"Your build configuration included 'failOnErrors=true', and %d error(s) were found on all checked pages. See %s for a detailed report.",
nrOfFindingsOnAllPages, config.getJunitResultsDir()
);
throw new MojoExecutionException(failureMsg);
}
}
// end::maven-plugin-implementation[]

private void logBuildParameter() {
void createoutputDirs(File dir, String failMessage) throws MojoExecutionException {
dir.mkdirs();
if (!dir.isDirectory() || !dir.canWrite()) {
throw new MojoExecutionException(failMessage);
}
}


void logBuildParameter() {
// Log build parameters
getLog().info(String.join("", Collections.nCopies(70, "=")));
getLog().info("Parameters given to sanityCheck plugin from Maven buildfile...");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,100 @@
package org.aim42.htmlsanitycheck.maven;

import org.aim42.htmlsanitycheck.Configuration;

import org.apache.maven.plugin.MojoExecutionException;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Assumptions;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;

class HtmlSanityCheckMojoTest {
@Test
void setupConfiguration() {
HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();
Configuration config = mojo.setupConfiguration();
Assertions.assertThat(config).isNotNull();
Assertions.assertThat(config.getFailOnErrors()).isFalse();
}


@Test
void logBuildParameter() {

// Write System.out and System.err to a stream. Keep the originals
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));

// Run the code
HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();
mojo.logBuildParameter();

// Reset System.out and System.err
System.setOut(originalOut);
System.setErr(originalErr);


// Check Output
Assertions.assertThat(errContent.toString()).isEmpty();
Assertions.assertThat(outContent.toString())
.contains("[info] Parameters given to sanityCheck plugin from Maven buildfile...")
.contains("[info] Files to check : null");
}

@Test
void createoutputDirs() throws IOException, MojoExecutionException {

// Set stage - Get a directory to safely work on and a mojo
Path tempDir = Files.createTempDirectory("MojoTest");

Assumptions.assumeThat(tempDir).isNotNull();

Path path = tempDir.resolve("testdir/anotherTestdir/dir");

HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();

// The code to test
mojo.createoutputDirs(path.toFile(), "Fehlertext");

// Check
Assertions.assertThat(path.toFile().exists()).isTrue();
Assertions.assertThat(path.toFile().canWrite()).isTrue();
Assertions.assertThat(path.toFile().isDirectory()).isTrue();

// Clean up
Files.deleteIfExists(path);
Files.deleteIfExists(tempDir.resolve("testdir/anotherTestdir"));
Files.deleteIfExists(tempDir.resolve("testdir"));
Files.deleteIfExists(tempDir);
}


@Test
void handleFindings() throws IOException {
// Set stage - Get a directory to safely work on, a configuration and a mojo
Path tempDir = Files.createTempDirectory("MojoTest");
Configuration config = Configuration.builder()
.failOnErrors(true)
.checkingResultsDir(tempDir.toFile())
.build();
HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();

//Check
Assertions.assertThatThrownBy(() -> mojo.handleFindings(2, config))
.isInstanceOf(MojoExecutionException.class)
.hasMessageContaining("2 error(s)");

// Clea uo
Files.deleteIfExists(tempDir);
}
}


}

0 comments on commit 1aa4133

Please sign in to comment.