Skip to content

Commit

Permalink
Issue checkstyle#4592: Added the last few tests which extend Abstract…
Browse files Browse the repository at this point in the history
…ModuleTestSupport
  • Loading branch information
subkrish committed Jul 29, 2017
1 parent acdbc55 commit fa285a1
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 227 deletions.
Expand Up @@ -67,7 +67,7 @@ protected static void verifyAst(String expectedTextPrintFileName, String actualJ

/**
* Performs verification of the given text ast tree representation.
* This implementation uses {@link BaseCheckTestSupport#verifyAst(String, String, boolean)}
* This implementation uses {@link AbstractTreeTestSupport#verifyAst(String, String, boolean)}
* method inside.
* @param expectedTextPrintFileName expected text ast tree representation.
* @param actualJavaFileName actual text ast tree representation.
Expand Down
Expand Up @@ -29,29 +29,26 @@
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;

/**
* @deprecated BaseCheckTestSupport is no longer used. All checks
* now extend AbstractPathTestSupport, AbstractModuleTestSupport,
* AbstractTreeTestSupport
*/
@Deprecated
public class BaseCheckTestSupport {
protected static final String LF_REGEX = "\\\\n";

protected static final String CLRF_REGEX = "\\\\r\\\\n";

private final ByteArrayOutputStream stream = new ByteArrayOutputStream();

Expand Down Expand Up @@ -115,115 +112,6 @@ protected String getPath(String filename) throws IOException {
.getCanonicalPath();
}

/**
* Returns URI-representation of the path for the given file name.
* The path is formed base on the root location.
* This implementation uses 'src/test/resources/com/puppycrawl/tools/checkstyle/'
* as a root location.
* @param filename file name.
* @deprecated This method is now used in AbstractModuleTestSupport.
* @return URI-representation of the path for the file with the given file name.
*/
@Deprecated
protected String getUriString(String filename) {
return new File("src/test/resources/com/puppycrawl/tools/checkstyle/" + filename).toURI()
.toString();
}

/**
* Returns canonical path for the file with the given file name.
* The path is formed base on the non-compilable resources location.
* This implementation uses 'src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/'
* as a non-compilable resource location.
* @param filename file name.
* @return canonical path for the file with the given file name.
* @throws IOException if I/O exception occurs while forming the path.
*/
protected String getNonCompilablePath(String filename) throws IOException {
return new File("src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/"
+ filename).getCanonicalPath();
}

/**
* Performs verification of the given text ast tree representation.
* This implementation uses {@link BaseCheckTestSupport#verifyAst(String, String, boolean)}
* method inside.
* @param expectedTextPrintFileName expected text ast tree representation.
* @param actualJavaFileName actual text ast tree representation.
* @throws Exception if exception occurs during verification.
*/
protected static void verifyAst(String expectedTextPrintFileName, String actualJavaFileName)
throws Exception {
verifyAst(expectedTextPrintFileName, actualJavaFileName, false);
}

/**
* Performs verification of the given text ast tree representation.
* @param expectedTextPrintFileName expected text ast tree representation.
* @param actualJavaFileName actual text ast tree representation.
* @param withComments whether to perform verification of comment nodes in tree.
* @throws Exception if exception occurs during verification.
*/
protected static void verifyAst(String expectedTextPrintFileName, String actualJavaFileName,
boolean withComments) throws Exception {
final String expectedContents = readFile(expectedTextPrintFileName);

final String actualContents = AstTreeStringPrinter.printFileAst(
new File(actualJavaFileName), withComments).replaceAll(CLRF_REGEX, LF_REGEX);

assertEquals("Generated AST from Java file should match pre-defined AST", expectedContents,
actualContents);
}

/**
* Verifies the javadoc tree generated for the supplied javadoc file against the expected tree
* in the supplied text file.
* @param expectedTextPrintFilename name of the text file having the expected tree.
* @param actualJavadocFilename name of the file containing the javadoc.
* @throws Exception if exception occurs during verification.
*/
protected static void verifyJavadocTree(String expectedTextPrintFilename,
String actualJavadocFilename) throws Exception {

final String expectedContents = readFile(expectedTextPrintFilename);

final String actualContents = DetailNodeTreeStringPrinter.printFileAst(
new File(actualJavadocFilename)).replaceAll(CLRF_REGEX, LF_REGEX);

assertEquals("Generated tree from the javadoc file should match the pre-defined tree",
expectedContents, actualContents);
}

/**
* Verifies the java and javadoc AST generated for the supplied java file against
* the expected AST in supplied text file.
* @param expectedTextPrintFilename name of the file having the expected ast.
* @param actualJavaFilename name of the java file.
* @throws Exception if exception occurs during verification.
*/
protected static void verifyJavaAndJavadocAst(String expectedTextPrintFilename,
String actualJavaFilename) throws Exception {

final String expectedContents = readFile(expectedTextPrintFilename);

final String actualContents = AstTreeStringPrinter.printJavaAndJavadocTree(
new File(actualJavaFilename)).replaceAll(CLRF_REGEX, LF_REGEX);

assertEquals("Generated AST from the java file should match the pre-defined AST",
expectedContents, actualContents);
}

/** Reads the contents of a file.
* @param filename the name of the file whose contents are to be read
* @return contents of the file with all {@code \r\n} replaced by {@code \n}
* @throws IOException if I/O exception occurs while reading
*/
protected static String readFile(String filename) throws IOException {
return new String(Files.readAllBytes(
Paths.get(filename)), StandardCharsets.UTF_8)
.replaceAll(CLRF_REGEX, LF_REGEX);
}

/**
* Performs verification of the file with the given file name. Uses specified configuration.
* Expected messages are represented by the array of strings.
Expand Down Expand Up @@ -397,67 +285,4 @@ private Map<String, List<String>> getActualViolations(int errorCount) throws IOE
return actualViolations;
}
}

/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
*/
protected String getCheckMessage(String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(), messageKey, arguments);
}

/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param clazz the related check class.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
*/
protected static String getCheckMessage(
Class<?> clazz, String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(clazz.getName()), messageKey, arguments);
}

/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param messageBundle the bundle name.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
*/
private static String internalGetCheckMessage(
String messageBundle, String messageKey, Object... arguments) {
final ResourceBundle resourceBundle = ResourceBundle.getBundle(
messageBundle,
Locale.getDefault(),
Thread.currentThread().getContextClassLoader(),
new LocalizedMessage.Utf8Control());
final String pattern = resourceBundle.getString(messageKey);
final MessageFormat formatter = new MessageFormat(pattern, Locale.ROOT);
return formatter.format(arguments);
}

private String getMessageBundle() {
final String className = getClass().getName();
return getMessageBundle(className);
}

private static String getMessageBundle(String className) {
final String messageBundle;
final String messages = "messages";
final int endIndex = className.lastIndexOf('.');
if (endIndex < 0) {
messageBundle = messages;
}
else {
final String packageName = className.substring(0, endIndex);
messageBundle = packageName + "." + messages;
}
return messageBundle;
}
}
41 changes: 24 additions & 17 deletions src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
Expand Up @@ -76,7 +76,9 @@
import com.puppycrawl.tools.checkstyle.filters.SuppressionFilter;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;

public class CheckerTest extends BaseCheckTestSupport {

//@noinspection ClassWithTooManyDependencies
public class CheckerTest extends AbstractModuleTestSupport {

@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
Expand All @@ -95,6 +97,11 @@ private static Method getFireAuditStartedMethod() throws NoSuchMethodException {
return fireAuditStarted;
}

@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle";
}

@Test
public void testDestroy() throws Exception {
final Checker checker = new Checker();
Expand Down Expand Up @@ -471,9 +478,9 @@ public void testCacheAndCheckWhichDoesNotImplementExternalResourceHolderInterfac
throws Exception {
assertFalse("ExternalResourceHolder has changed his parent",
ExternalResourceHolder.class.isAssignableFrom(HiddenFieldCheck.class));
final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class);
final DefaultConfiguration checkConfig = createModuleConfig(HiddenFieldCheck.class);

final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class);
final DefaultConfiguration treeWalkerConfig = createModuleConfig(TreeWalker.class);
treeWalkerConfig.addChild(checkConfig);

final DefaultConfiguration checkerConfig = new DefaultConfiguration("checkstyleConfig");
Expand Down Expand Up @@ -513,12 +520,12 @@ public void testWithCacheWithNoViolation() throws Exception {
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
checker.configure(createCheckConfig(TranslationCheck.class));
checker.configure(createModuleConfig(TranslationCheck.class));

final File cacheFile = temporaryFolder.newFile();
checker.setCacheFile(cacheFile.getPath());

checker.setupChild(createCheckConfig(TranslationCheck.class));
checker.setupChild(createModuleConfig(TranslationCheck.class));
final File tmpFile = temporaryFolder.newFile("file.java");
final List<File> files = new ArrayList<>(1);
files.add(tmpFile);
Expand Down Expand Up @@ -589,7 +596,7 @@ public void testClearExistingCache() throws Exception {
@Test
public void testClearCache() throws Exception {
final DefaultConfiguration violationCheck =
createCheckConfig(DummyFileSetViolationCheck.class);
createModuleConfig(DummyFileSetViolationCheck.class);
final DefaultConfiguration checkerConfig = new DefaultConfiguration("myConfig");
checkerConfig.addAttribute("charset", "UTF-8");
final File cacheFile = temporaryFolder.newFile();
Expand Down Expand Up @@ -674,7 +681,7 @@ public void testCacheAndFilterWhichDoesNotImplementExternalResourceHolderInterfa
throws Exception {
assertFalse("ExternalResourceHolder has changed its parent",
ExternalResourceHolder.class.isAssignableFrom(DummyFilter.class));
final DefaultConfiguration filterConfig = createCheckConfig(DummyFilter.class);
final DefaultConfiguration filterConfig = createModuleConfig(DummyFilter.class);

final DefaultConfiguration checkerConfig = new DefaultConfiguration("checkstyle_checks");
checkerConfig.addChild(filterConfig);
Expand Down Expand Up @@ -795,11 +802,11 @@ public void testCacheAndCheckWhichAddsNewResourceLocationButKeepsSameCheckerInst
@Test
public void testClearLazyLoadCacheInDetailAST() throws Exception {
final DefaultConfiguration checkConfig1 =
createCheckConfig(CheckWhichDoesNotRequireCommentNodes.class);
createModuleConfig(CheckWhichDoesNotRequireCommentNodes.class);
final DefaultConfiguration checkConfig2 =
createCheckConfig(CheckWhichRequiresCommentNodes.class);
createModuleConfig(CheckWhichRequiresCommentNodes.class);

final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class);
final DefaultConfiguration treeWalkerConfig = createModuleConfig(TreeWalker.class);
treeWalkerConfig.addChild(checkConfig1);
treeWalkerConfig.addChild(checkConfig2);

Expand All @@ -821,12 +828,12 @@ public void testClearLazyLoadCacheInDetailAST() throws Exception {
public void testCacheOnViolationSuppression() throws Exception {
final File cacheFile = temporaryFolder.newFile();
final DefaultConfiguration violationCheck =
createCheckConfig(DummyFileSetViolationCheck.class);
createModuleConfig(DummyFileSetViolationCheck.class);
final DefaultConfiguration defaultConfig = new DefaultConfiguration("defaultConfiguration");
defaultConfig.addAttribute("cacheFile", cacheFile.getPath());
defaultConfig.addChild(violationCheck);

final DefaultConfiguration filterConfig = createCheckConfig(SuppressionFilter.class);
final DefaultConfiguration filterConfig = createModuleConfig(SuppressionFilter.class);
filterConfig.addAttribute("file", getPath("suppress_all.xml"));
defaultConfig.addChild(filterConfig);

Expand All @@ -852,9 +859,9 @@ public void testCacheOnViolationSuppression() throws Exception {
@Test
public void testHaltOnExceptionOff() throws Exception {
final DefaultConfiguration checkConfig =
createCheckConfig(CheckWhichThrowsError.class);
createModuleConfig(CheckWhichThrowsError.class);

final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class);
final DefaultConfiguration treeWalkerConfig = createModuleConfig(TreeWalker.class);
treeWalkerConfig.addChild(checkConfig);

final DefaultConfiguration checkerConfig = new DefaultConfiguration("checkstyleConfig");
Expand Down Expand Up @@ -912,7 +919,7 @@ public Object createModule(String name) throws CheckstyleException {
}
};
checker.setModuleFactory(factory);
checker.setupChild(createCheckConfig(DebugAuditAdapter.class));
checker.setupChild(createModuleConfig(DebugAuditAdapter.class));
// Let's try fire some events
checker.process(Collections.singletonList(new File("dummy.java")));
assertTrue("Checker.fireAuditStarted() doesn't call listener", auditAdapter.wasCalled());
Expand All @@ -934,7 +941,7 @@ public Object createModule(String name) throws CheckstyleException {
}
};
checker.setModuleFactory(factory);
checker.setupChild(createCheckConfig(TestBeforeExecutionFileFilter.class));
checker.setupChild(createModuleConfig(TestBeforeExecutionFileFilter.class));
checker.process(Collections.singletonList(new File("dummy.java")));
assertTrue("Checker.acceptFileStarted() doesn't call listener", fileFilter.wasCalled());
}
Expand All @@ -956,7 +963,7 @@ public Object createModule(String name) throws CheckstyleException {
};
checker.setModuleFactory(factory);
checker.finishLocalSetup();
checker.setupChild(createCheckConfig(DummyFileSet.class));
checker.setupChild(createModuleConfig(DummyFileSet.class));
assertTrue("FileSetCheck.init() wasn't called", fileSet.isInitCalled());
}

Expand Down

0 comments on commit fa285a1

Please sign in to comment.