Skip to content

Commit

Permalink
Pull checkstyle#10827: reworks JavadocMetadataScrapperTest to make mo…
Browse files Browse the repository at this point in the history
…re sense
  • Loading branch information
rnveach authored and pbludov committed Oct 2, 2021
1 parent 0da7491 commit 9c1297e
Show file tree
Hide file tree
Showing 27 changed files with 725 additions and 293 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,20 @@ public class JavadocMetadataScraper extends AbstractJavadocCheck {
*/
private int parentSectionStartIdx;

/**
* Control whether to write XML output or not.
*/
private boolean writeXmlOutput = true;

/**
* Setter to control whether to write XML output or not.
*
* @param writeXmlOutput whether to write XML output or not.
*/
public final void setWriteXmlOutput(boolean writeXmlOutput) {
this.writeXmlOutput = writeXmlOutput;
}

@Override
public int[] getDefaultJavadocTokens() {
return new int[] {
Expand Down Expand Up @@ -213,10 +227,7 @@ else if (ast.getType() == JavadocTokenTypes.SINCE_LITERAL) {
public void finishJavadocTree(DetailNode rootAst) {
moduleDetails.setDescription(getDescriptionText());
if (isTopLevelClassJavadoc()) {
if (getFileContents().getFileName().contains("test")) {
MODULE_DETAILS_STORE.put(moduleDetails.getFullQualifiedName(), moduleDetails);
}
else {
if (writeXmlOutput) {
try {
XmlMetaWriter.write(moduleDetails);
}
Expand All @@ -225,6 +236,9 @@ public void finishJavadocTree(DetailNode rootAst) {
+ "module: " + getModuleSimpleName(), ex);
}
}
else {
MODULE_DETAILS_STORE.put(moduleDetails.getFullQualifiedName(), moduleDetails);
}
}
}

Expand All @@ -234,7 +248,7 @@ public void finishJavadocTree(DetailNode rootAst) {
*
* @param ast javadoc ast
*/
public void scrapeContent(DetailNode ast) {
private void scrapeContent(DetailNode ast) {
if (ast.getType() == JavadocTokenTypes.PARAGRAPH) {
if (isParentText(ast)) {
parentSectionStartIdx = getParentIndexOf(ast);
Expand Down Expand Up @@ -603,13 +617,18 @@ public static Map<String, ModuleDetails> getModuleDetailsStore() {
return Collections.unmodifiableMap(MODULE_DETAILS_STORE);
}

/** Reset the module detail store of any previous information. */
public static void resetModuleDetailsStore() {
MODULE_DETAILS_STORE.clear();
}

/**
* Check if the current javadoc block comment AST corresponds to the top-level class as we
* only want to scrape top-level class javadoc.
*
* @return true if the current AST corresponds to top level class
*/
public boolean isTopLevelClassJavadoc() {
private boolean isTopLevelClassJavadoc() {
final DetailAST parent = getParent(getBlockCommentAst());
final Optional<DetailAST> className = TokenUtil
.findFirstTokenByPredicate(parent, child -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ private MetadataGeneratorUtil() {
* @throws CheckstyleException checkstyleException
*/
public static void generate(String... args) throws IOException, CheckstyleException {
JavadocMetadataScraper.resetModuleDetailsStore();

final Checker checker = new Checker();
checker.setModuleClassLoader(Checker.class.getClassLoader());
final DefaultConfiguration scraperCheckConfig =
Expand All @@ -76,23 +78,18 @@ public static void generate(String... args) throws IOException, CheckstyleExcept
private static void dumpMetadata(Checker checker, String path) throws CheckstyleException,
IOException {
final List<File> validFiles = new ArrayList<>();
if (path.endsWith(".java")) {
validFiles.add(new File(path));
}
else {
final List<String> moduleFolders = Arrays.asList("checks", "filters", "filefilters");
for (String folder : moduleFolders) {
try (Stream<Path> files = Files.walk(Paths.get(path
+ "/" + folder))) {
validFiles.addAll(
files.map(Path::toFile)
.filter(file -> {
return file.getName().endsWith("SuppressWarningsHolder.java")
|| file.getName().endsWith("Check.java")
|| file.getName().endsWith("Filter.java");
})
.collect(Collectors.toList()));
}
final List<String> moduleFolders = Arrays.asList("checks", "filters", "filefilters");
for (String folder : moduleFolders) {
try (Stream<Path> files = Files.walk(Paths.get(path
+ "/" + folder))) {
validFiles.addAll(
files.map(Path::toFile)
.filter(file -> {
return file.getName().endsWith("SuppressWarningsHolder.java")
|| file.getName().endsWith("Check.java")
|| file.getName().endsWith("Filter.java");
})
.collect(Collectors.toList()));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,34 +19,225 @@

package com.puppycrawl.tools.checkstyle.meta;

import static org.junit.jupiter.api.Assertions.assertNull;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

import java.util.Map;
import java.util.Map.Entry;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class JavadocMetadataScraperTest {
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;

private static final String CHECK_PACKAGE_BASE =
"com.puppycrawl.tools.checkstyle.meta.javadocmetadatascraper.checks.";
public class JavadocMetadataScraperTest extends AbstractModuleTestSupport {

private static Map<String, ModuleDetails> moduleDetailsStore;
@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/meta/javadocmetadatascraper";
}

@Test
public void testAtclauseOrderCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(getPath("InputJavadocMetadataScraperAtclauseOrderCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperAtclauseOrderCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testAnnotationUseStyleCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperAnnotationUseStyleCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperAnnotationUseStyleCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testBeforeExecutionExclusionFileFilter() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperBeforeExecutionExclusionFileFilter.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(
readFile(getPath(
"ExpectedJavadocMetadataScraperBeforeExecutionExclusionFileFilter.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testNoCodeInFileCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(getPath("InputJavadocMetadataScraperNoCodeInFileCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperNoCodeInFileCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testPropertyMisplacedDefaultValueCheck() {
JavadocMetadataScraper.resetModuleDetailsStore();
final CheckstyleException exc = assertThrows(CheckstyleException.class, () -> {
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperPropertyMisplacedDefaultValueCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
});
assertThat(exc.getCause()).isInstanceOf(MetadataGenerationException.class);
assertThat(exc.getCause().getMessage())
.isEqualTo("Default value for property 'misplacedDefaultValue' is missing");
}

@BeforeAll
public static void fillModuleDetailsStore() throws Exception {
MetadataGeneratorUtil.generate(System.getProperty("user.dir")
+ "/src/test/resources/com/puppycrawl/tools/checkstyle"
+ "/meta/javadocmetadatascraper");
moduleDetailsStore = JavadocMetadataScraper.getModuleDetailsStore();
@Test
public void testPropertyMisplacedTypeCheck() {
JavadocMetadataScraper.resetModuleDetailsStore();
final CheckstyleException exc = assertThrows(CheckstyleException.class, () -> {
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperPropertyMisplacedTypeCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
fail("Exception expected");
});
assertThat(exc.getCause()).isInstanceOf(MetadataGenerationException.class);
assertThat(exc.getCause().getMessage())
.isEqualTo("Type for property 'misplacedType' is missing");
}

@Test
public void testPropertyNameWithNoCodeTag() {
final String testCheck = "custom.InputJavadocMetadataScraperPropertyWithNoCodeTagCheck";
final ModuleDetails testCheckMeta = moduleDetailsStore.get(CHECK_PACKAGE_BASE + testCheck);
public void testPropertyMissingDefaultValueCheck() {
JavadocMetadataScraper.resetModuleDetailsStore();
final CheckstyleException exc = assertThrows(CheckstyleException.class, () -> {
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperPropertyMissingDefaultValueCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
fail("Exception expected");
});
assertThat(exc.getCause()).isInstanceOf(MetadataGenerationException.class);
assertThat(exc.getCause().getMessage())
.isEqualTo("Default value for property 'missingDefaultValue' is missing");
}

@Test
public void testPropertyMissingTypeCheck() {
JavadocMetadataScraper.resetModuleDetailsStore();
final CheckstyleException exc = assertThrows(CheckstyleException.class, () -> {
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperPropertyMissingTypeCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
fail("Exception expected");
});
assertThat(exc.getCause()).isInstanceOf(MetadataGenerationException.class);
assertThat(exc.getCause().getMessage())
.isEqualTo("Type for property 'missingType' is missing");
}

@Test
public void testPropertyWithNoCodeTagCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperPropertyWithNoCodeTagCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(
readFile(getPath("ExpectedJavadocMetadataScraperPropertyWithNoCodeTagCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testRightCurlyCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(getPath("InputJavadocMetadataScraperRightCurlyCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperRightCurlyCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testSummaryJavadocCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(getPath("InputJavadocMetadataScraperSummaryJavadocCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperSummaryJavadocCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testSuppressWarningsFilter() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(
getPath("InputJavadocMetadataScraperSuppressWarningsFilter.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperSuppressWarningsFilter.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

@Test
public void testWriteTagCheck() throws Exception {
JavadocMetadataScraper.resetModuleDetailsStore();
verifyWithInlineConfigParser(getPath("InputJavadocMetadataScraperWriteTagCheck.java"),
CommonUtil.EMPTY_STRING_ARRAY);
assertEquals(readFile(getPath("ExpectedJavadocMetadataScraperWriteTagCheck.txt")),
convertToString(JavadocMetadataScraper.getModuleDetailsStore()),
"expected correct parse");
}

private static String convertToString(Map<String, ModuleDetails> moduleDetailsStore) {
final StringBuilder builder = new StringBuilder(128);
for (Entry<String, ModuleDetails> entry : moduleDetailsStore.entrySet()) {
final ModuleDetails details = entry.getValue();

append(builder, "Key: ", split(entry.getKey(), 70));
append(builder, "Name: ", details.getName());
append(builder, "FullQualifiedName: ", split(details.getFullQualifiedName(), 70));
append(builder, "Parent: ", details.getParent());
append(builder, "Description: ", details.getDescription());
append(builder, "ModuleType: ", details.getModuleType());

for (ModulePropertyDetails property : details.getProperties()) {
append(builder, "Property Type: ", split(property.getType(), 70));
append(builder, "Property DefaultValue: ", split(property.getDefaultValue(), 70));
append(builder, "Property ValidationType: ", property.getValidationType());
append(builder, "Property Description: ", property.getDescription());
}

for (String key : details.getViolationMessageKeys()) {
append(builder, "ViolationMessageKey: ", key);
}
}
return builder.toString();
}

private static void append(StringBuilder builder, String title, Object object) {
builder.append(title).append(object).append('\n');
}

assertNull(testCheckMeta.getProperties().get(0).getName(),
"Check with no property name {@code } tag should have null property name");
private static String split(String text, int size) {
final StringBuilder builder = new StringBuilder(80);
if (text == null) {
builder.append("null");
}
else {
final int length = text.length();
int position = 0;
while (position < length) {
if (position != 0) {
builder.append("<split>\n");
}
builder.append(text, position, Math.min(length, position + size));
position += size;
}
}
return builder.toString();
}
}
Loading

0 comments on commit 9c1297e

Please sign in to comment.