Skip to content

Issue #41: Updated AbstractRecipeTest to remove external report #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@
</dependency>

<!-- Test dependencies -->
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>${checkstyle.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openrewrite</groupId>
<artifactId>rewrite-test</artifactId>
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/org/checkstyle/autofix/recipe/Header.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class Header extends Recipe {
private static final String HEADER_FILE_PROPERTY = "headerFile";
private static final String IGNORE_LINES_PROPERTY = "ignoreLines";
private static final String CHARSET_PROPERTY = "charset";
private static final String LINE_SEPRATOR = "\n";

private final List<CheckstyleViolation> violations;
private final Configuration config;
Expand Down Expand Up @@ -149,7 +150,7 @@ public J visit(Tree tree, ExecutionContext ctx) {
currentHeader, ignoreLines);

sourceFile = sourceFile.withPrefix(
Space.format(fixedHeader + System.lineSeparator()));
Space.format(fixedHeader + LINE_SEPRATOR));
}
result = super.visit(sourceFile, ctx);
}
Expand Down Expand Up @@ -186,7 +187,7 @@ private static String fixHeaderLines(String licenseHeader,
}
}

return String.join(System.lineSeparator(), currentLines);
return String.join(LINE_SEPRATOR, currentLines);
}

private boolean hasViolation(Path filePath) {
Expand Down
11 changes: 9 additions & 2 deletions src/main/java/org/checkstyle/autofix/recipe/UpperEll.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,13 @@ private int computeLinePosition(J tree, J targetElement, Cursor cursor) {
}

private int computeColumnPosition(J tree, J targetElement, Cursor cursor) {
return computePosition(tree, targetElement, cursor, this::calculateColumnOffset);
return computePosition(tree, targetElement, cursor, out -> {
int column = calculateColumnOffset(out);
if (((J.Literal) targetElement).getValueSource().matches("^[+-].*")) {
column++;
}
return column;
});
}

private int calculateColumnOffset(String out) {
Expand All @@ -176,8 +182,9 @@ private int calculateColumnOffset(String out) {
result = out.length();
}
else {
result = out.length() - lineBreakIndex - 1;
result = out.length() - lineBreakIndex;
}

return result;
}

Expand Down
122 changes: 98 additions & 24 deletions src/test/java/org/checkstyle/autofix/recipe/AbstractRecipeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,62 +20,136 @@
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.openrewrite.java.Assertions.java;

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.checkstyle.autofix.InputClassRenamer;
import org.checkstyle.autofix.parser.CheckstyleReportParser;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.openrewrite.Recipe;
import org.openrewrite.test.RewriteTest;

import com.puppycrawl.tools.checkstyle.AbstractXmlTestSupport;
import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.XMLLogger;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.bdd.InlineConfigParser;
import com.puppycrawl.tools.checkstyle.bdd.TestInputConfiguration;

public abstract class AbstractRecipeTest implements RewriteTest {
public abstract class AbstractRecipeTest extends AbstractXmlTestSupport implements RewriteTest {

private static final String BASE_TEST_RESOURCES_PATH = "src/test/resources/org"
+ "/checkstyle/autofix/recipe/";
protected abstract String getSubpackage();

protected abstract String getCheckName();

protected abstract Recipe createRecipe(List<CheckstyleViolation> violations,
Configuration configuration);

@Override
protected String getPackageLocation() {
return "org/checkstyle/autofix/recipe/" + getSubpackage();
}

private Recipe createPreprocessingRecipe() {
return new InputClassRenamer();
}

protected abstract Recipe getRecipe() throws CheckstyleException;
protected void verify(String testCaseName) throws Exception {
final String inputFileName = "Input" + testCaseName + ".java";
final String outputFileName = "Output" + testCaseName + ".java";
final String inputPath = testCaseName.toLowerCase() + "/" + inputFileName;
final String outputPath = testCaseName.toLowerCase() + "/" + outputFileName;

final Configuration config = getAllCheckConfigurations(inputPath);
final List<CheckstyleViolation> violations = runCheckstyle(inputPath, config);
final Configuration checkConfig = extractCheckConfiguration(config, getCheckName());

final String beforeCode = readFile(getPath(inputPath));
final String expectedAfterCode = readFile(getPath(outputPath));
final Recipe mainRecipe = createRecipe(violations, checkConfig);

testRecipe(beforeCode, expectedAfterCode,
getPath(inputPath), createPreprocessingRecipe(), mainRecipe);
}

protected void testRecipe(String recipePath, String testCaseName) throws IOException,
CheckstyleException {
final String testCaseDir = testCaseName.toLowerCase();
protected void verify(Configuration checkConfig, String testCaseName) throws Exception {
final String inputFileName = "Input" + testCaseName + ".java";
final String outputFileName = "Output" + testCaseName + ".java";
final String inputPath = testCaseName.toLowerCase() + "/" + inputFileName;
final String outputPath = testCaseName.toLowerCase() + "/" + outputFileName;

final List<CheckstyleViolation> violations = runCheckstyle(inputPath, checkConfig);

final String beforeCode = Files.readString(Paths.get(BASE_TEST_RESOURCES_PATH
+ recipePath + "/" + testCaseDir + "/" + inputFileName));
final String beforeCode = readFile(getPath(inputPath));
final String expectedAfterCode = readFile(getPath(outputPath));

final String afterCode = Files.readString(Paths.get(BASE_TEST_RESOURCES_PATH
+ recipePath + "/" + testCaseDir + "/" + outputFileName));
final Recipe mainRecipe = createRecipe(violations, checkConfig);

final Recipe preprocessing = createPreprocessingRecipe();
final Recipe mainRecipe = getRecipe();
testRecipe(beforeCode, expectedAfterCode,
getPath(inputPath), createPreprocessingRecipe(), mainRecipe);
}

private List<CheckstyleViolation> runCheckstyle(String inputPath,
Configuration config) throws Exception {

final Checker checker = createChecker(config);
final ByteArrayOutputStream xmlOutput = new ByteArrayOutputStream();
final XMLLogger logger = new XMLLogger(xmlOutput, XMLLogger.OutputStreamOptions.CLOSE);
checker.addListener(logger);

final List<File> filesToCheck = Collections.singletonList(new File(getPath(inputPath)));
checker.process(filesToCheck);

final Path tempXmlPath = Files.createTempFile("checkstyle-report", ".xml");
try {
Files.write(tempXmlPath, xmlOutput.toByteArray());
return CheckstyleReportParser.parse(tempXmlPath);
}
finally {
Files.deleteIfExists(tempXmlPath);
}
}

private Configuration getAllCheckConfigurations(String inputPath) throws Exception {
final String configFilePath = getPath(inputPath);
final TestInputConfiguration testInputConfiguration =
InlineConfigParser.parse(configFilePath);
return testInputConfiguration.createConfiguration();
}

private void testRecipe(String beforeCode, String expectedAfterCode,
String filePath, Recipe... recipes) {
assertDoesNotThrow(() -> {
rewriteRun(
spec -> spec.recipes(preprocessing, mainRecipe),
java(beforeCode, afterCode)
spec -> spec.recipes(recipes),
java(beforeCode, expectedAfterCode, spec -> spec.path(filePath))
);
});
}

protected Configuration extractCheckConfiguration(Configuration config, String checkName) {

return Arrays.stream(config.getChildren())
return Optional.of(config)
.filter(child -> checkName.equals(child.getName()))
.findFirst()
.orElseThrow(() -> {
return new IllegalArgumentException(checkName + "configuration not "
+ "found");
});
.orElse(Arrays.stream(config.getChildren())
.filter(child -> {
return "com.puppycrawl.tools.checkstyle.TreeWalker"
.equals(child.getName());
})
.flatMap(treeWalker -> Arrays.stream(treeWalker.getChildren()))
.filter(child -> checkName.equals(child.getName()))
.findFirst()
.orElseThrow(() -> {
return new IllegalArgumentException(checkName
+ " configuration not found");
}));
}

protected Charset getCharset(Configuration config) {
Expand Down
60 changes: 33 additions & 27 deletions src/test/java/org/checkstyle/autofix/recipe/HeaderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,55 +17,61 @@

package org.checkstyle.autofix.recipe;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

import org.checkstyle.autofix.parser.CheckstyleReportParser;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.junit.jupiter.api.Test;
import org.openrewrite.Recipe;

import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
import com.puppycrawl.tools.checkstyle.PropertiesExpander;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck;

public class HeaderTest extends AbstractRecipeTest {

@Override
protected Recipe getRecipe() throws CheckstyleException {
final String reportPath = "src/test/resources/org/checkstyle/autofix/recipe/header"
+ "/report.xml";

final String configPath = "src/test/resources/org/checkstyle/autofix/recipe/header"
+ "/config.xml";
protected String getSubpackage() {
return "header";
}

final Configuration config = ConfigurationLoader.loadConfiguration(
configPath, new PropertiesExpander(new Properties())
);
@Override
protected String getCheckName() {
return "Header";
}

final List<CheckstyleViolation> violations =
CheckstyleReportParser.parse(Path.of(reportPath));
@Override
protected Recipe createRecipe(List<CheckstyleViolation> violations, Configuration config) {

return new Header(violations,
extractCheckConfiguration(config, "Header"), getCharset(config));
return new Header(violations, config, getCharset(config));
}

@Test
void headerTest() throws IOException, CheckstyleException {
testRecipe("header", "HeaderBlankLines");
void headerTest() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class);
final String headerPath = "src/test/resources/org/checkstyle/autofix/"
+ "recipe/header/header.txt";
checkConfig.addProperty("headerFile", headerPath);
checkConfig.addProperty("ignoreLines", "3");
verify(checkConfig, "HeaderBlankLines");
}

@Test
void headerCommentTest() throws IOException, CheckstyleException {
testRecipe("header", "HeaderComments");
void headerCommentTest() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class);
final String headerPath = "src/test/resources/org/checkstyle/autofix/"
+ "recipe/header/header.txt";
checkConfig.addProperty("headerFile", headerPath);
checkConfig.addProperty("ignoreLines", "3");
verify(checkConfig, "HeaderComments");
}

@Test
void headerIncorrect() throws IOException, CheckstyleException {
testRecipe("header", "HeaderIncorrect");
void headerIncorrect() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class);
final String headerPath = "src/test/resources/org/checkstyle/"
+ "autofix/recipe/header/header.txt";
checkConfig.addProperty("headerFile", headerPath);
checkConfig.addProperty("ignoreLines", "3");
verify(checkConfig, "HeaderIncorrect");
}

}
33 changes: 18 additions & 15 deletions src/test/java/org/checkstyle/autofix/recipe/UpperEllTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,41 +17,44 @@

package org.checkstyle.autofix.recipe;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import org.checkstyle.autofix.parser.CheckstyleReportParser;
import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.junit.jupiter.api.Test;
import org.openrewrite.Recipe;

import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;

public class UpperEllTest extends AbstractRecipeTest {

@Override
protected Recipe getRecipe() {
final String reportPath = "src/test/resources/org/checkstyle/autofix/recipe/upperell"
+ "/report.xml";
protected String getSubpackage() {
return "upperell";
}

@Override
protected String getCheckName() {
return "com.puppycrawl.tools.checkstyle.checks.UpperEllCheck";
}

@Override
protected Recipe createRecipe(List<CheckstyleViolation> violations, Configuration config) {

final List<CheckstyleViolation> violations =
CheckstyleReportParser.parse(Path.of(reportPath));
return new UpperEll(violations);
}

@Test
void hexOctalLiteralTest() throws IOException, CheckstyleException {
testRecipe("upperell", "HexOctalLiteral");
void hexOctalLiteral() throws Exception {
verify("HexOctalLiteral");
}

@Test
void complexLongLiterals() throws IOException, CheckstyleException {
testRecipe("upperell", "ComplexLongLiterals");
void complexLongLiterals() throws Exception {
verify("ComplexLongLiterals");
}

@Test
void stringAndCommentTest() throws IOException, CheckstyleException {
testRecipe("upperell", "StringAndComments");
void stringAndComments() throws Exception {
verify("StringAndComments");
}
}
15 changes: 0 additions & 15 deletions src/test/resources/org/checkstyle/autofix/recipe/header/config.xml

This file was deleted.

Loading