Skip to content

Commit

Permalink
#314 Increase test coverage on mojo
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Ruhroth authored and ascheman committed Jan 6, 2025
1 parent 79a4047 commit ccefb2b
Show file tree
Hide file tree
Showing 3 changed files with 236 additions and 42 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,60 +183,72 @@ 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);
return allChecksRunner.performAllChecks();
} catch (IOException e) {
throw new MojoExecutionException(e);
}
}

// tag::maven-plugin-implementation[]
public void execute() throws MojoExecutionException {
logBuildParameter();

// Setup configuration
Configuration myConfig = setupConfiguration();
execute(setupConfiguration());
}

void execute(Configuration myConfig) throws MojoExecutionException {
// Check if configuration is valid
logBuildParameter(myConfig);
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(Configuration myConfig) {
// Log build parameters
getLog().info(String.join("", Collections.nCopies(70, "=")));
getLog().info("Parameters given to sanityCheck plugin from Maven buildfile...");
getLog().info("Files to check : " + sourceDocuments);
getLog().info("Source directory: " + sourceDir);
getLog().info("Results dir : " + checkingResultsDir);
getLog().info("JUnit dir : " + junitResultsDir);
getLog().info("Fail on errors : " + failOnErrors);
getLog().info("Files to check : " + myConfig.getSourceDocuments());
getLog().info("Source directory: " + myConfig.getSourceDir());
getLog().info("Results dir : " + myConfig.getCheckingResultsDir());
getLog().info("JUnit dir : " + myConfig.getJunitResultsDir());
getLog().info("Fail on errors : " + myConfig.getFailOnErrors());
}

protected Configuration setupConfiguration() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,197 @@
package org.aim42.htmlsanitycheck.maven;

import org.aim42.htmlsanitycheck.Configuration;

import org.aim42.htmlsanitycheck.check.AllCheckers;
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.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Set;

class HtmlSanityCheckMojoTest {

final static String VALID_HTML = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"><html><head></head><body></body><html>";

@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();
PrintStream originalOut = System.out;
System.setOut(new PrintStream(outContent));

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

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


// Check Output
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();
Assertions.assertThat(path.toFile()).canWrite();
Assertions.assertThat(path.toFile()).isDirectory();

// Clean up
deleteDirectory(tempDir.toFile());
}

@Test
void createoutputDirsFail() throws IOException {

// Set stage - Create a File, that is no dir to provoke an exception and create a mojo
Path tempDir = Files.createTempFile("MojoTest", "");

Assumptions.assumeThat(tempDir).isNotNull();

HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();

// Check
Assertions.assertThatThrownBy(() -> mojo.createoutputDirs(tempDir.toFile(), "Fehlertext"))
.isInstanceOf(MojoExecutionException.class)
.hasMessageContaining("Fehlertext");

// Clean up
Files.deleteIfExists(tempDir);
}


@Test
void handleFindingsThrowsException() 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)");

// Clean up
Files.deleteIfExists(tempDir);
}

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

//Check, dass keine Exception fliegt

mojo.handleFindings(2, config);

// Clean up
Files.deleteIfExists(tempDir);
}
}


@Test
void handleFindingsNoExceptionIfNoFindings() throws IOException, MojoExecutionException {
// 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, dass keine Exception fliegt

mojo.handleFindings(0, config);

// Clean up
Files.deleteIfExists(tempDir);
}

@Test
void execute() throws IOException, MojoExecutionException {
Path junitDir = Files.createTempDirectory("MojoJunit");
Path resultDir = Files.createTempDirectory("MojoJunit");
Path sourceDir = Files.createTempDirectory("MojoSource");
sourceDir.toFile().deleteOnExit();
File sourceFile = new File(sourceDir.toFile(), "test.html");
Files.write(sourceFile.toPath(), VALID_HTML.getBytes(StandardCharsets.UTF_8));
Set<File> fileset = new HashSet<>();
fileset.add(sourceFile);

Configuration myConfig = Configuration.builder()
.checksToExecute(AllCheckers.CHECKER_CLASSES)
.junitResultsDir(junitDir.toFile())
.checkingResultsDir(resultDir.toFile())
.sourceDir(sourceDir.toFile())
.sourceDocuments(fileset)
.build();
HtmlSanityCheckMojo mojo = new HtmlSanityCheckMojo();

mojo.execute(myConfig);


// Clean up
deleteDirectory(junitDir.toFile());
deleteDirectory(resultDir.toFile());
}


// Helper functions

void deleteDirectory(File directoryToBeDeleted) throws IOException {
File[] allContents = directoryToBeDeleted.listFiles();
if (allContents != null) {
for (File file : allContents) {
deleteDirectory(file);
}
}
Files.deleteIfExists(directoryToBeDeleted.toPath());
}


}

0 comments on commit ccefb2b

Please sign in to comment.