diff options
Diffstat (limited to 'src/test/java/com/puppycrawl/tools/checkstyle')
105 files changed, 1859 insertions, 621 deletions
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java index b3e708a0c..5b008cf2e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java @@ -81,7 +81,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * Returns test logger. * @return logger for tests */ - public BriefUtLogger getBriefUtLogger() { + public final BriefUtLogger getBriefUtLogger() { return new BriefUtLogger(stream); } @@ -95,7 +95,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @return {@link Checker} instance based on the given {@link Configuration} instance. * @throws Exception if an exception occurs during checker configuration. */ - public Checker createChecker(Configuration moduleConfig) + public final Checker createChecker(Configuration moduleConfig) throws Exception { ModuleCreationOption moduleCreationOption = ModuleCreationOption.IN_CHECKER; @@ -103,7 +103,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport if (!ROOT_MODULE_NAME.equals(moduleName)) { try { final Class<?> moduleClass = Class.forName(moduleName); - if (ModuleReflectionUtils.isCheckstyleCheck(moduleClass) + if (ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(moduleClass) || ModuleReflectionUtils.isTreeWalkerFilterModule(moduleClass)) { moduleCreationOption = ModuleCreationOption.IN_TREEWALKER; } @@ -124,7 +124,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @return {@link Checker} instance based on the given {@link Configuration} instance. * @throws Exception if an exception occurs during checker configuration. */ - public Checker createChecker(Configuration moduleConfig, + public final Checker createChecker(Configuration moduleConfig, ModuleCreationOption moduleCreationOption) throws Exception { final Checker checker = new Checker(); @@ -150,9 +150,9 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * based on the given {@link Configuration} instance. * @param config {@link Configuration} instance. * @return {@link DefaultConfiguration} for the {@link TreeWalker} - * based on the given {@link Configuration} instance. + * based on the given {@link Configuration} instance. */ - protected DefaultConfiguration createTreeWalkerConfig(Configuration config) { + protected static DefaultConfiguration createTreeWalkerConfig(Configuration config) { final DefaultConfiguration dc = new DefaultConfiguration("configuration"); final DefaultConfiguration twConf = createModuleConfig(TreeWalker.class); @@ -168,7 +168,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @param config {@link Configuration} instance. * @return {@link DefaultConfiguration} for the given {@link Configuration} instance. */ - protected DefaultConfiguration createRootConfig(Configuration config) { + protected static DefaultConfiguration createRootConfig(Configuration config) { final DefaultConfiguration dc = new DefaultConfiguration(ROOT_MODULE_NAME); if (config != null) { dc.addChild(config); @@ -198,7 +198,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @param filename file name. * @return URI-representation of the path for the file with the given file name. */ - protected String getUriString(String filename) { + protected final String getUriString(String filename) { return new File("src/test/resources/" + getPackageLocation() + "/" + filename).toURI() .toString(); } @@ -213,7 +213,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @param expected an array of expected messages. * @throws Exception if exception occurs during verification process. */ - protected void verify(Configuration aConfig, String fileName, String... expected) + protected final void verify(Configuration aConfig, String fileName, String... expected) throws Exception { verify(createChecker(aConfig), fileName, fileName, expected); } @@ -246,7 +246,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @param expected an array of expected messages. * @throws Exception if exception occurs during verification process. */ - protected void verify(Checker checker, + protected final void verify(Checker checker, String processedFilename, String messageFileName, String... expected) @@ -257,8 +257,13 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport } /** - * We keep two verify methods with separate logic only for convenience of debugging - * We have minimum amount of multi-file test cases + * We keep two verify methods with separate logic only for convenience of debugging. + * We have minimum amount of multi-file test cases. + * @param checker {@link Checker} instance. + * @param processedFiles list of files to verify. + * @param messageFileName message file name. + * @param expected an array of expected messages. + * @throws Exception if exception occurs during verification process. */ protected void verify(Checker checker, File[] processedFiles, @@ -299,7 +304,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @param expectedViolations a map of expected violations per files. * @throws Exception if exception occurs during verification process. */ - protected void verify(Checker checker, + protected final void verify(Checker checker, File[] processedFiles, Map<String, List<String>> expectedViolations) throws Exception { @@ -383,8 +388,9 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * * @param messageKey the key of message in 'messages.properties' file. * @param arguments the arguments of message in 'messages.properties' file. + * @return The message of the check with the arguments applied. */ - protected String getCheckMessage(String messageKey, Object... arguments) { + protected final String getCheckMessage(String messageKey, Object... arguments) { return internalGetCheckMessage(getMessageBundle(), messageKey, arguments); } @@ -395,6 +401,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @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. + * @return The message of the check with the arguments applied. */ protected static String getCheckMessage( Class<?> clazz, String messageKey, Object... arguments) { @@ -408,6 +415,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport * @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. + * @return The message of the check with the arguments applied. */ private static String internalGetCheckMessage( String messageBundle, String messageKey, Object... arguments) { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java index 9b79d8f59..849cf8981 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java @@ -21,8 +21,15 @@ package com.puppycrawl.tools.checkstyle; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; public abstract class AbstractPathTestSupport { + protected static final String LF_REGEX = "\\\\n"; + + protected static final String CRLF_REGEX = "\\\\r\\\\n"; + /** * Returns the exact location for the package where the file is present. * @return path for the package name for the file. @@ -46,4 +53,15 @@ public abstract class AbstractPathTestSupport { protected final String getResourcePath(String filename) { return "/" + getPackageLocation() + "/" + filename; } + + /** 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(CRLF_REGEX, LF_REGEX); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java index dd676666b..01113fa95 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java @@ -23,16 +23,9 @@ import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; public abstract class AbstractTreeTestSupport extends AbstractPathTestSupport { - protected static final String LF_REGEX = "\\\\n"; - - protected static final String CRLF_REGEX = "\\\\r\\\\n"; - /** * Returns canonical path for the file with the given file name. * The path is formed base on the non-compilable resources location. @@ -118,15 +111,4 @@ public abstract class AbstractTreeTestSupport extends AbstractPathTestSupport { assertEquals("Generated tree from the javadoc file should match the pre-defined tree", 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(CRLF_REGEX, LF_REGEX); - } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java new file mode 100644 index 000000000..9387ec28b --- /dev/null +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java @@ -0,0 +1,171 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.puppycrawl.tools.checkstyle; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.function.BiPredicate; + +import javax.xml.parsers.ParserConfigurationException; + +import org.junit.Assert; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil; + +public abstract class AbstractXmlTestSupport extends AbstractModuleTestSupport { + + protected static Document getOutputStreamXml(ByteArrayOutputStream outputStream) + throws ParserConfigurationException { + final String xml = new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + + return XmlUtil.getRawXml("audit output", xml, xml); + } + + protected static void verifyXml(String expectedOutputFile, + ByteArrayOutputStream actualOutputStream, String... messages) throws Exception { + verifyXml(expectedOutputFile, actualOutputStream, null, messages); + } + + protected static void verifyXml(String expectedOutputFile, + ByteArrayOutputStream actualOutputStream, + BiPredicate<Node, Node> ordered, String... messages) throws Exception { + String expectedContents = readFile(expectedOutputFile); + + for (int i = 0; i < messages.length; i++) { + expectedContents = expectedContents.replace("$" + i, messages[i]); + } + + final Document expectedDocument = XmlUtil.getRawXml("audit output", expectedContents, + expectedContents); + final Document actualDocument = getOutputStreamXml(actualOutputStream); + + verifyXmlNode(expectedDocument, actualDocument, "/", ordered); + } + + private static void verifyXmlNodes(Node expected, Node actual, String path, + BiPredicate<Node, Node> ordered) { + final Node expectedFirstChild = expected.getFirstChild(); + final Node actualFirstChild = actual.getFirstChild(); + + if (expectedFirstChild == null) { + Assert.assertNull("no children nodes should exist: " + path, actualFirstChild); + Assert.assertEquals("text should be the same: " + path, expected.getNodeValue(), + actual.getNodeValue()); + } + else { + Assert.assertNotNull("children nodes should exist: " + path, actualFirstChild); + + if (ordered == null) { + Node actualChild = actualFirstChild; + + for (Node expectedChild = expectedFirstChild; expectedChild != null; + expectedChild = expectedChild.getNextSibling()) { + verifyXmlNode(expectedChild, actualChild, path, ordered); + + actualChild = actualChild.getNextSibling(); + } + + Assert.assertNull("node have same number of children: " + path, actualChild); + } + else { + final Set<Node> expectedChildren = XmlUtil.getChildrenElements(expected); + final Set<Node> actualChildren = XmlUtil.getChildrenElements(actual); + + Assert.assertEquals("node have same number of children: " + path, + expectedChildren.size(), actualChildren.size()); + + for (Node expectedChild : expectedChildren) { + Node foundChild = null; + + for (Node actualChild : actualChildren) { + if (ordered.test(expectedChild, actualChild)) { + foundChild = actualChild; + break; + } + } + + Assert.assertNotNull("node should exist: " + path + expectedChild.getNodeName() + + "/", foundChild); + + verifyXmlNode(expectedChild, foundChild, path, ordered); + } + } + } + } + + private static void verifyXmlNode(Node expected, Node actual, String path, + BiPredicate<Node, Node> ordered) { + if (expected == null) { + if (actual != null) { + Assert.fail("no node should exist: " + path + actual.getNodeName() + "/"); + } + } + else { + final String newPath = path + expected.getNodeName() + "/"; + + Assert.assertNotNull("node should exist: " + newPath, actual); + Assert.assertEquals("node should have same name: " + newPath, expected.getNodeName(), + actual.getNodeName()); + Assert.assertEquals("node should have same type: " + newPath, expected.getNodeType(), + actual.getNodeType()); + + verifyXmlAttributes(expected.getAttributes(), actual.getAttributes(), newPath); + + verifyXmlNodes(expected, actual, newPath, ordered); + } + } + + private static void verifyXmlAttributes(NamedNodeMap expected, NamedNodeMap actual, + String path) { + if (expected == null) { + Assert.assertNull("no attributes should exist: " + path, actual); + } + else { + Assert.assertNotNull("attributes should exist: " + path, actual); + + for (int i = 0; i < expected.getLength(); i++) { + verifyXmlAttribute(expected.item(i), actual.item(i), path); + } + + Assert.assertEquals("node have same number of attributes: " + path, + expected.getLength(), actual.getLength()); + } + } + + private static void verifyXmlAttribute(Node expected, Node actual, String path) { + final String expectedName = expected.getNodeName(); + + Assert.assertNotNull("attribute value for '" + expectedName + "' should not be null: " + + path, actual); + + Assert.assertEquals("attribute name should match: " + path, expectedName, + actual.getNodeName()); + + // ignore checkstyle version in xml as it changes each release + if (!"/#document/checkstyle".equals(path) && !"version".equals(expectedName)) { + Assert.assertEquals("attribute value for '" + expectedName + "' should match: " + path, + expected.getNodeValue(), actual.getNodeValue()); + } + } +} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java index 876492e7f..a59c27ea0 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java @@ -415,7 +415,7 @@ public class CheckerTest extends AbstractModuleTestSupport { assertEquals("Charset was different than expected", System.getProperty("file.encoding", StandardCharsets.UTF_8.name()), context.get("charset")); - assertEquals("Was used unsufficient classloader", + assertEquals("Was used insufficient classloader", contextClassLoader, context.get("classLoader")); assertEquals("Severity is set to unexpected value", "error", context.get("severity")); @@ -1079,7 +1079,7 @@ public class CheckerTest extends AbstractModuleTestSupport { @Override public Set<String> getExternalResourceLocations() { final Set<String> externalResourceLocation = new HashSet<>(1); - externalResourceLocation.add("non_existing_external_resource.xml"); + externalResourceLocation.add("non_existent_external_resource.xml"); return externalResourceLocation; } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java index 3e43563e2..909fed3ee 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java @@ -511,16 +511,16 @@ public class ConfigurationLoaderTest extends AbstractPathTestSupport { } @Test - public void testNonExistingPropertyName() throws Exception { + public void testNonExistentPropertyName() throws Exception { try { - loadConfiguration("InputConfigurationLoaderNonexistingProperty.xml"); + loadConfiguration("InputConfigurationLoaderNonexistentProperty.xml"); fail("exception in expected"); } catch (CheckstyleException ex) { assertEquals("Invalid exception message", "unable to parse configuration stream", ex.getMessage()); assertEquals("Invalid exception cause message", - "Property ${nonexisting} has not been set", + "Property ${nonexistent} has not been set", ex.getCause().getMessage()); } } @@ -619,7 +619,7 @@ public class ConfigurationLoaderTest extends AbstractPathTestSupport { /** * This SuppressWarning("unchecked") required to suppress - * "Unchecked generics array creation for varargs parameter" during mock + * "Unchecked generics array creation for varargs parameter" during mock. * @throws Exception could happen from PowerMokito calls and getAttribute */ @SuppressWarnings("unchecked") diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java index de4d5a975..07ede0057 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java @@ -32,18 +32,18 @@ public class DefaultConfigurationTest { public void testRemoveChild() { final DefaultConfiguration config = new DefaultConfiguration("MyConfig"); final DefaultConfiguration configChild = new DefaultConfiguration("childConfig"); - assertEquals("Invalid cildren count", 0, config.getChildren().length); + assertEquals("Invalid children count", 0, config.getChildren().length); config.addChild(configChild); - assertEquals("Invalid cildren count", 1, config.getChildren().length); + assertEquals("Invalid children count", 1, config.getChildren().length); config.removeChild(configChild); - assertEquals("Invalid cildren count", 0, config.getChildren().length); + assertEquals("Invalid children count", 0, config.getChildren().length); } @Test - public void testExceptionForNonExistingAttribute() { + public void testExceptionForNonExistentAttribute() { final String name = "MyConfig"; final DefaultConfiguration config = new DefaultConfiguration(name); - final String attributeName = "NonExisting#$%"; + final String attributeName = "NonExistent#$%"; try { config.getAttribute(attributeName); fail("Exception is expected"); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java index 654da102d..a339424a0 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java @@ -19,6 +19,7 @@ package com.puppycrawl.tools.checkstyle; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -33,6 +34,7 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; @@ -114,4 +116,15 @@ public class DefaultLoggerTest { assertTrue("Message should contain exception info, but was " + infoStream, infoStream.toString().contains("java.lang.IllegalStateException: upsss")); } + + @Test + public void testFinishLocalSetup() throws CheckstyleException { + final OutputStream infoStream = new ByteArrayOutputStream(); + final DefaultLogger dl = new DefaultLogger(infoStream, + AutomaticBean.OutputStreamOptions.CLOSE); + dl.finishLocalSetup(); + dl.auditStarted(null); + dl.auditFinished(null); + assertNotNull("instance should not be null", dl); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java index e6f46a06a..6d77ef350 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java @@ -77,7 +77,7 @@ public class DetailNodeTreeStringPrinterTest extends AbstractTreeTestSupport { } @Test - public void testNoUnnecessaryTextinJavadocAst() throws Exception { + public void testNoUnnecessaryTextInJavadocAst() throws Exception { verifyJavadocTree( getPath("ExpectedDetailNodeTreeStringPrinterNoUnnecessaryTextInJavadocAst.txt"), getPath("InputDetailNodeTreeStringPrinterNoUnnecessaryTextInJavadocAst.javadoc")); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java index 77b8d4a30..a29340b4a 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java @@ -173,7 +173,7 @@ public class MainTest { throws Exception { exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", + assertEquals("Unexpected output log", "Checkstyle version: null" + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); @@ -188,7 +188,7 @@ public class MainTest { exit.checkAssertionAfterwards(() -> { final String usage = "Unrecognized option: -w" + EOL + USAGE; - assertEquals("Unexpected ouput log", usage, systemOut.getLog()); + assertEquals("Unexpected output log", usage, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-w"); @@ -199,7 +199,7 @@ public class MainTest { throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", + assertEquals("Unexpected output log", "Must specify a config XML file." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); @@ -208,36 +208,36 @@ public class MainTest { } @Test - public void testNonExistingTargetFile() + public void testNonExistentTargetFile() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Files to process must be specified, found 0." + assertEquals("Unexpected output log", "Files to process must be specified, found 0." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); - Main.main("-c", "/google_checks.xml", "NonExistingFile.java"); + Main.main("-c", "/google_checks.xml", "NonExistentFile.java"); } @Test - public void testNonExistingConfigFile() + public void testNonExistentConfigFile() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Could not find config XML file " - + "'src/main/resources/non_existing_config.xml'." + EOL, + assertEquals("Unexpected output log", "Could not find config XML file " + + "'src/main/resources/non_existent_config.xml'." + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); - Main.main("-c", "src/main/resources/non_existing_config.xml", + Main.main("-c", "src/main/resources/non_existent_config.xml", getPath("InputMain.java")); } @Test - public void testNonExistingOutputFormat() throws Exception { + public void testNonExistentOutputFormat() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Invalid output format. " + assertEquals("Unexpected output log", "Invalid output format. " + "Found 'xmlp' but expected 'plain' or 'xml'." + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -246,19 +246,18 @@ public class MainTest { } @Test - public void testNonExistingClass() throws Exception { + public void testNonExistentClass() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { - final String expectedExceptionMessage = errorCounterOneMessage.getMessage() - + EOL; - assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog()); + final String expectedExceptionMessage = errorCounterOneMessage.getMessage() + EOL; + assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog()); final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:" + " cannot initialize module TreeWalker - "; assertTrue("Unexpected system error log", systemErr.getLog().startsWith(cause)); }); - Main.main("-c", getPath("InputMainConfig-non-existing-classname.xml"), + Main.main("-c", getPath("InputMainConfig-non-existent-classname.xml"), getPath("InputMain.java")); } @@ -266,7 +265,7 @@ public class MainTest { public void testExistingTargetFile() throws Exception { exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL + assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + auditFinishMessage.getMessage() + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); @@ -284,7 +283,7 @@ public class MainTest { ResourceBundle.getBundle("checkstylecompilation", Locale.ROOT); final String version = compilationProperties .getString("checkstyle.compile.version"); - assertEquals("Unexpected ouput log", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + EOL + assertEquals("Unexpected output log", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + EOL + "<checkstyle version=\"" + version + "\">" + EOL + "<file name=\"" + expectedPath + "\">" + EOL + "</file>" + EOL @@ -300,7 +299,7 @@ public class MainTest { public void testExistingTargetFilePlainOutput() throws Exception { exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL + assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + auditFinishMessage.getMessage() + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -321,7 +320,7 @@ public class MainTest { "name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"}, null, getClass(), null); final String expectedPath = getFilePath("InputMain.java"); - assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL + assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + "[WARN] " + expectedPath + ":3:14: " + invalidPatternMessageMain.getMessage() + " [TypeName]" + EOL @@ -352,7 +351,7 @@ public class MainTest { "name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"}, null, getClass(), null); final String expectedPath = getFilePath("InputMain.java"); - assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL + assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + "[ERROR] " + expectedPath + ":3:14: " + invalidPatternMessageMain.getMessage() + " [TypeName]" + EOL + "[ERROR] " + expectedPath + ":5:7: " @@ -367,11 +366,11 @@ public class MainTest { } @Test - public void testExistingTargetFilePlainOutputToNonExistingFile() + public void testExistentTargetFilePlainOutputToNonExistentFile() throws Exception { exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-classname.xml"), @@ -385,7 +384,7 @@ public class MainTest { throws Exception { final File file = temporaryFolder.newFile("file.output"); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-classname.xml"), @@ -395,8 +394,8 @@ public class MainTest { } @Test - public void testCreateNonExistingOutputFile() throws Exception { - final String outputFile = temporaryFolder.getRoot().getCanonicalPath() + "nonexisting.out"; + public void testCreateNonExistentOutputFile() throws Exception { + final String outputFile = temporaryFolder.getRoot().getCanonicalPath() + "nonexistent.out"; assertFalse("File must not exist", new File(outputFile).exists()); Main.main("-c", getPath("InputMainConfig-classname.xml"), "-f", "plain", @@ -413,7 +412,7 @@ public class MainTest { //exit.expectSystemExitWithStatus(0); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL + assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL + auditFinishMessage.getMessage() + EOL, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -426,16 +425,16 @@ public class MainTest { } @Test - public void testExistingTargetFilePlainOutputNonexistingProperties() + public void testExistingTargetFilePlainOutputNonexistentProperties() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Could not find file 'nonexisting.properties'." + assertEquals("Unexpected output log", "Could not find file 'nonexistent.properties'." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-classname-prop.xml"), - "-p", "nonexisting.properties", + "-p", "nonexistent.properties", getPath("InputMain.java")); } @@ -445,7 +444,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String output = errorCounterOneMessage.getMessage() + EOL; - assertEquals("Unexpected ouput log", output, systemOut.getLog()); + assertEquals("Unexpected output log", output, systemOut.getLog()); final String errorOutput = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: unable to parse configuration stream - "; assertTrue("Unexpected system error log", systemErr.getLog().startsWith(errorOutput)); @@ -460,7 +459,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String output = errorCounterOneMessage.getMessage() + EOL; - assertEquals("Unexpected ouput log", output, systemOut.getLog()); + assertEquals("Unexpected output log", output, systemOut.getLog()); final String errorOutput = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: cannot initialize module RegexpSingleline" + " - RegexpSingleline is not allowed as a child in RegexpSingleline"; @@ -476,7 +475,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String output = errorCounterOneMessage.getMessage() + EOL; - assertEquals("Unexpected ouput log", output, systemOut.getLog()); + assertEquals("Unexpected output log", output, systemOut.getLog()); final String errorOutput = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: cannot initialize module TreeWalker" + " - JavadocVariable is not allowed as a child in JavadocMethod"; @@ -521,12 +520,12 @@ public class MainTest { final boolean samePrefix = causeMessage.substring(0, causeMessage.indexOf(' ')) .equals(localizedMessage .substring(0, localizedMessage.indexOf(' '))); - final boolean sameSufix = + final boolean sameSuffix = causeMessage.substring(causeMessage.lastIndexOf(' '), causeMessage.length()) .equals(localizedMessage .substring(localizedMessage.lastIndexOf(' '), localizedMessage.length())); - assertTrue("Invalid error message", samePrefix || sameSufix); + assertTrue("Invalid error message", samePrefix || sameSuffix); assertTrue("Invalid error message", causeMessage.contains(":invalid")); } @@ -614,7 +613,7 @@ public class MainTest { } sb.append(auditFinishMessage.getMessage()) .append(EOL); - assertEquals("Unexpected ouput log", sb.toString(), systemOut.getLog()); + assertEquals("Unexpected output log", sb.toString(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -659,7 +658,7 @@ public class MainTest { exit.checkAssertionAfterwards(() -> { final String expectedExceptionMessage = auditStartMessage.getMessage() + EOL + errorCounterOneMessage.getMessage() + EOL; - assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog()); + assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog()); final String exceptionFirstLine = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: Exception was thrown while processing " @@ -669,7 +668,7 @@ public class MainTest { systemErr.getLog().startsWith(exceptionFirstLine)); }); - // We put xml as source to cause parse excepion + // We put xml as source to cause parse exception Main.main("-c", getPath("InputMainConfig-classname.xml"), getNonCompilablePath("InputMainIncorrectClass.java")); } @@ -679,7 +678,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Printing AST is allowed for only one file." + assertEquals("Unexpected output log", "Printing AST is allowed for only one file." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -718,7 +717,7 @@ public class MainTest { + " `--RCURLY -> } [6:0]" + EOL; exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", expected, systemOut.getLog()); + assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-t", getPath("InputMain.java")); @@ -758,7 +757,7 @@ public class MainTest { + " `--RCURLY -> } [6:0]" + EOL; exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", expected, systemOut.getLog()); + assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-T", getPath("InputMain.java")); @@ -771,7 +770,7 @@ public class MainTest { .replaceAll("\\\\r\\\\n", "\\\\n"); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", + assertEquals("Unexpected output log", expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n")); assertEquals("Unexpected system error log", "", systemErr.getLog()); @@ -786,7 +785,7 @@ public class MainTest { StandardCharsets.UTF_8).replaceAll("\\\\r\\\\n", "\\\\n"); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", + assertEquals("Unexpected output log", expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n")); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -798,7 +797,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options." + assertEquals("Unexpected output log", "Option '-t' cannot be used with other options." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -811,7 +810,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options." + assertEquals("Unexpected output log", "Option '-t' cannot be used with other options." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -824,7 +823,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options." + assertEquals("Unexpected output log", "Option '-t' cannot be used with other options." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -838,7 +837,7 @@ public class MainTest { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options." + assertEquals("Unexpected output log", "Option '-t' cannot be used with other options." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -857,7 +856,7 @@ public class MainTest { public void testExcludeOption() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Files to process must be specified, found 0." + assertEquals("Unexpected output log", "Files to process must be specified, found 0." + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -868,9 +867,9 @@ public class MainTest { public void testExcludeRegexpOption() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Files to process must be specified, found 0." + assertEquals("Unexpected output log", "Files to process must be specified, found 0." + System.lineSeparator(), systemOut.getLog()); - assertEquals("Unexpected ouput log", "", systemErr.getLog()); + assertEquals("Unexpected output log", "", systemErr.getLog()); }); Main.main("-c", "/google_checks.xml", getFilePath(""), "-x", "."); } @@ -893,7 +892,7 @@ public class MainTest { TestRootModuleChecker.reset(); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); assertTrue("Invalid Checker state", TestRootModuleChecker.isProcessed()); }); @@ -916,7 +915,7 @@ public class MainTest { + "TestRootModuleCheckerCheck, " + checkstylePackage + "TestRootModuleCheckerCheck"}, null, getClass(), null); - assertEquals("Unexpected ouput log", errorCounterOneMessage.getMessage() + EOL, + assertEquals("Unexpected output log", errorCounterOneMessage.getMessage() + EOL, systemOut.getLog()); assertTrue("Unexpected system error log", systemErr.getLog().startsWith(checkstylePackage + "api.CheckstyleException: " @@ -932,14 +931,14 @@ public class MainTest { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String expectedExceptionMessage = errorCounterOneMessage.getMessage() + EOL; - assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog()); + assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog()); final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:" + " cannot initialize module TreeWalker - "; assertTrue("Unexpected system error log", systemErr.getLog().startsWith(cause)); }); - Main.main("-c", getPath("InputMainConfig-non-existing-classname-ignore.xml"), + Main.main("-c", getPath("InputMainConfig-non-existent-classname-ignore.xml"), "-executeIgnoredModules", getPath("InputMain.java")); } @@ -948,7 +947,7 @@ public class MainTest { public void testInvalidCheckerThreadsNumber() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Invalid Checker threads number" + assertEquals("Unexpected output log", "Invalid Checker threads number" + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -959,7 +958,7 @@ public class MainTest { public void testInvalidTreeWalkerThreadsNumber() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Invalid TreeWalker threads number" + assertEquals("Unexpected output log", "Invalid TreeWalker threads number" + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -970,7 +969,7 @@ public class MainTest { public void testZeroCheckerThreadsNumber() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "Checker threads number must be greater than zero" + assertEquals("Unexpected output log", "Checker threads number must be greater than zero" + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); @@ -981,7 +980,7 @@ public class MainTest { public void testZeroTreeWalkerThreadsNumber() throws Exception { exit.expectSystemExitWithStatus(-1); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", + assertEquals("Unexpected output log", "TreeWalker threads number must be greater than zero" + System.lineSeparator(), systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); @@ -994,7 +993,7 @@ public class MainTest { TestRootModuleChecker.reset(); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed()); final DefaultConfiguration config = @@ -1014,7 +1013,7 @@ public class MainTest { TestRootModuleChecker.reset(); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed()); final DefaultConfiguration config = @@ -1034,7 +1033,7 @@ public class MainTest { TestRootModuleChecker.reset(); exit.checkAssertionAfterwards(() -> { - assertEquals("Unexpected ouput log", "", systemOut.getLog()); + assertEquals("Unexpected output log", "", systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed()); final DefaultConfiguration config = @@ -1049,7 +1048,7 @@ public class MainTest { .getChildren()[0]; assertEquals("Invalid checker name", "Checker", checkerConfiguration.getName()); final Configuration treeWalkerConfig = checkerConfiguration.getChildren()[0]; - assertEquals("Invalid checker childs name", "TreeWalker", treeWalkerConfig.getName()); + assertEquals("Invalid checker children name", "TreeWalker", treeWalkerConfig.getName()); }); Main.main("-C", "1", "-W", "1", "-c", getPath("InputMainConfig-multi-thread-mode.xml"), getPath("InputMain.java")); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java index d391e64ea..cf9823825 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java @@ -109,11 +109,11 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { final String filePath = temporaryFolder.newFile().getPath(); final PropertyCacheFile cache = new PropertyCacheFile(config, filePath); cache.put("myFile", 1); - assertTrue("Should return true wnen file is in cache", + assertTrue("Should return true when file is in cache", cache.isInCache("myFile", 1)); - assertFalse("Should return false wnen file is not in cache", + assertFalse("Should return false when file is not in cache", cache.isInCache("myFile", 2)); - assertFalse("Should return false wnen file is not in cache", + assertFalse("Should return false when file is not in cache", cache.isInCache("myFile1", 1)); } @@ -216,7 +216,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { } @Test - public void testExternalResourseIsSavedInCache() throws Exception { + public void testExternalResourceIsSavedInCache() throws Exception { final Configuration config = new DefaultConfiguration("myName"); final String filePath = temporaryFolder.newFile().getPath(); final PropertyCacheFile cache = new PropertyCacheFile(config, filePath); @@ -245,12 +245,12 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { /** * This SuppressWarning("unchecked") required to suppress - * "Unchecked generics array creation for varargs parameter" during mock + * "Unchecked generics array creation for varargs parameter" during mock. * @throws IOException when smth wrong with file creation or cache.load */ @SuppressWarnings("unchecked") @Test - public void testNonExistingResource() throws IOException { + public void testNonExistentResource() throws IOException { final Configuration config = new DefaultConfiguration("myName"); final String filePath = temporaryFolder.newFile().getPath(); final PropertyCacheFile cache = new PropertyCacheFile(config, filePath); @@ -358,10 +358,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { } @Test - public void testPutNonExsistingExternalResourceSameExceptionBetweenRuns() throws Exception { + public void testPutNonExistentExternalResourceSameExceptionBetweenRuns() throws Exception { final File cacheFile = temporaryFolder.newFile(); - // We mock getUriByFilename method of CommonUtils to garantee that it will + // We mock getUriByFilename method of CommonUtils to guarantee that it will // throw CheckstyleException with the specific content. mockStatic(CommonUtils.class); final CheckstyleException mockException = @@ -370,7 +370,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { .thenThrow(mockException); // We invoke 'putExternalResources' twice to invalidate cache - // and have two identical exceptions whith the equal content + // and have two identical exceptions which the equal content final int numberOfRuns = 2; final String[] configHashes = new String[numberOfRuns]; final String[] externalResourceHashes = new String[numberOfRuns]; @@ -382,10 +382,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY); assertNotNull("Config hash key should not be null", configHashes[i]); - final Set<String> nonExistingExternalResources = new HashSet<>(); - final String externalResourceFileName = "non_existing_file.xml"; - nonExistingExternalResources.add(externalResourceFileName); - cache.putExternalResources(nonExistingExternalResources); + final Set<String> nonExistentExternalResources = new HashSet<>(); + final String externalResourceFileName = "non_existent_file.xml"; + nonExistentExternalResources.add(externalResourceFileName); + cache.putExternalResources(nonExistentExternalResources); externalResourceHashes[i] = cache.get(PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX + externalResourceFileName); @@ -412,7 +412,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { * @noinspection InstanceMethodNamingConvention */ @Test - public void testPutNonExsistingExternalResourceDifferentExceptionsBetweenRuns() + public void testPutNonExistentExternalResourceDifferentExceptionsBetweenRuns() throws Exception { final File cacheFile = temporaryFolder.newFile(); @@ -426,7 +426,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { final Configuration config = new DefaultConfiguration("myConfig"); final PropertyCacheFile cache = new PropertyCacheFile(config, cacheFile.getPath()); - // We mock getUriByFilename method of CommonUtils to garantee that it will + // We mock getUriByFilename method of CommonUtils to guarantee that it will // throw CheckstyleException with the specific content. mockStatic(CommonUtils.class); final CheckstyleException mockException = new CheckstyleException("Exception #" + i); @@ -438,10 +438,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport { configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY); assertNotNull("Config hash key should not be null", configHashes[i]); - final Set<String> nonExistingExternalResources = new HashSet<>(); - final String externalResourceFileName = "non_existing_file.xml"; - nonExistingExternalResources.add(externalResourceFileName); - cache.putExternalResources(nonExistingExternalResources); + final Set<String> nonExistentExternalResources = new HashSet<>(); + final String externalResourceFileName = "non_existent_file.xml"; + nonExistentExternalResources.add(externalResourceFileName); + cache.putExternalResources(nonExistentExternalResources); externalResourceHashes[i] = cache.get(PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX + externalResourceFileName); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java index 91464a9e8..cfb14357d 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java @@ -24,34 +24,32 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; import org.junit.Test; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AutomaticBean; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.internal.utils.CloseAndFlushTestByteArrayOutputStream; -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; /** * Enter a description of class XMLLoggerTest.java. * @author Rick Giles */ // -@cs[AbbreviationAsWordInName] Test should be named as its main class. -public class XMLLoggerTest { +public class XMLLoggerTest extends AbstractXmlTestSupport { private final CloseAndFlushTestByteArrayOutputStream outStream = new CloseAndFlushTestByteArrayOutputStream(); + @Override + protected String getPackageLocation() { + return "com/puppycrawl/tools/checkstyle/xmllogger"; + } + @Test public void testEncode() throws IOException { @@ -116,7 +114,7 @@ public class XMLLoggerTest { @Test public void testCloseStream() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, AutomaticBean.OutputStreamOptions.CLOSE); logger.auditStarted(null); @@ -124,13 +122,12 @@ public class XMLLoggerTest { assertEquals("Invalid close count", 1, outStream.getCloseCount()); - final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream); } @Test public void testNoCloseStream() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, AutomaticBean.OutputStreamOptions.NONE); logger.auditStarted(null); @@ -139,42 +136,34 @@ public class XMLLoggerTest { assertEquals("Invalid close count", 0, outStream.getCloseCount()); outStream.close(); - final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream); } @Test public void testFileStarted() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final AuditEvent ev = new AuditEvent(this, "Test.java"); logger.fileStarted(ev); + logger.fileFinished(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLogger.xml"), outStream); } @Test public void testFileFinished() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final AuditEvent ev = new AuditEvent(this, "Test.java"); logger.fileFinished(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLogger.xml"), outStream); } @Test - public void testAddError() throws IOException { + public void testAddError() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -182,19 +171,15 @@ public class XMLLoggerTest { "messages.properties", "key", null, SeverityLevel.ERROR, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "Test.java", message); + logger.fileStarted(ev); logger.addError(ev); + logger.fileFinished(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\"" - + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerError.xml"), outStream, message.getMessage()); } @Test - public void testAddErrorWithNullFileName() throws IOException { + public void testAddErrorWithNullFileName() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -204,15 +189,12 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, null, message); logger.addError(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\"" - + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerErrorNullFileName.xml"), outStream, + message.getMessage()); } @Test - public void testAddErrorModuleId() throws IOException { + public void testAddErrorModuleId() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -222,17 +204,11 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addError(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\"" - + " source=\"module\"/>", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerErrorModuleId.xml"), outStream, message.getMessage()); } @Test - public void testAddErrorOnZeroColumns() throws IOException { + public void testAddErrorOnZeroColumns() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -240,19 +216,16 @@ public class XMLLoggerTest { "messages.properties", "key", null, SeverityLevel.ERROR, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "Test.java", message); + logger.fileStarted(ev); logger.addError(ev); + logger.fileFinished(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<error line=\"1\" severity=\"error\" message=\"key\"" - + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerErrorZeroColumn.xml"), outStream, + message.getMessage()); } @Test - public void testAddIgnored() throws IOException { + public void testAddIgnored() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -262,13 +235,12 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addError(ev); logger.auditFinished(null); - final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream); } @Test public void testAddException() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -277,20 +249,13 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addException(ev, new TestException("msg", new RuntimeException("msg"))); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<exception> <![CDATA[ stackTrace example]]>" - + " </exception> ", - "</file>", - }; - - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerException.xml"), outStream); assertEquals("Invalid close count", 1, outStream.getCloseCount()); } @Test public void testAddExceptionWithNullFileName() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -299,18 +264,13 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, null, message); logger.addException(ev, new TestException("msg", new RuntimeException("msg"))); logger.auditFinished(null); - final String[] expectedLines = { - "<exception> <![CDATA[ stackTrace example]]>" - + " </exception> ", - }; - - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerExceptionNullFileName.xml"), outStream); assertEquals("Invalid close count", 1, outStream.getCloseCount()); } @Test public void testAddExceptionAfterFileStarted() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); @@ -323,21 +283,15 @@ public class XMLLoggerTest { final AuditEvent ev = new AuditEvent(this, "Test.java", message); logger.addException(ev, new TestException("msg", new RuntimeException("msg"))); + logger.fileFinished(ev); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<exception> <![CDATA[ stackTrace example]]>" - + " </exception> ", - "</file>", - }; - - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream); assertEquals("Invalid close count", 1, outStream.getCloseCount()); } @Test public void testAddExceptionBeforeFileFinished() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -348,20 +302,13 @@ public class XMLLoggerTest { final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java"); logger.fileFinished(fileFinishedEvent); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<exception> <![CDATA[ stackTrace example]]>" - + " </exception> ", - "</file>", - }; - - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerException3.xml"), outStream); assertEquals("Invalid close count", 1, outStream.getCloseCount()); } @Test public void testAddExceptionBetweenFileStartedAndFinished() - throws IOException { + throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final LocalizedMessage message = @@ -374,19 +321,12 @@ public class XMLLoggerTest { final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java"); logger.fileFinished(fileFinishedEvent); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<exception> <![CDATA[ stackTrace example]]>" - + " </exception> ", - "</file>", - }; - - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream); assertEquals("Invalid close count", 1, outStream.getCloseCount()); } @Test - public void testAuditFinishedWithoutFileFinished() throws IOException { + public void testAuditFinishedWithoutFileFinished() throws Exception { final XMLLogger logger = new XMLLogger(outStream, true); logger.auditStarted(null); final AuditEvent fileStartedEvent = new AuditEvent(this, "Test.java"); @@ -399,53 +339,18 @@ public class XMLLoggerTest { final AuditEvent errorEvent = new AuditEvent(this, "Test.java", message); logger.addError(errorEvent); + logger.fileFinished(errorEvent); logger.auditFinished(null); - final String[] expectedLines = { - "<file name=\"Test.java\">", - "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\"" - + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>", - "</file>", - }; - verifyLines(expectedLines); + verifyXml(getPath("ExpectedXMLLoggerError.xml"), outStream, message.getMessage()); } - private String[] getOutStreamLines() - throws IOException { - final byte[] bytes = outStream.toByteArray(); - final ByteArrayInputStream inStream = - new ByteArrayInputStream(bytes); - final List<String> lineList = new ArrayList<>(); - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(inStream, StandardCharsets.UTF_8))) { - while (true) { - final String line = reader.readLine(); - if (line == null) { - break; - } - lineList.add(line); - } - } - return lineList.toArray(new String[lineList.size()]); - } - - /** - * Verify output lines from auditStart to auditEnd. - * Take into consideration checkstyle element (first and last lines). - * @param expectedLines expected error report lines - */ - private void verifyLines(String... expectedLines) - throws IOException { - final String[] lines = getOutStreamLines(); - assertEquals("length.", expectedLines.length + 3, lines.length); - assertEquals("first line.", - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", - lines[0]); - final Pattern checkstyleOpenTag = Pattern.compile("^<checkstyle version=\".*\">$"); - assertTrue("second line.", checkstyleOpenTag.matcher(lines[1]).matches()); - for (int i = 0; i < expectedLines.length; i++) { - assertEquals("line " + i + ".", expectedLines[i], lines[i + 2]); - } - assertEquals("last line.", "</checkstyle>", lines[lines.length - 1]); + @Test + public void testFinishLocalSetup() throws CheckstyleException { + final XMLLogger logger = new XMLLogger(outStream, true); + logger.finishLocalSetup(); + logger.auditStarted(null); + logger.auditFinished(null); + assertNotNull("instance should not be null", logger); } private static class TestException extends RuntimeException { @@ -461,5 +366,4 @@ public class XMLLoggerTest { printWriter.print("stackTrace\r\nexample"); } } - } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/XmlLoaderTest.java index 80dd679d4..0c805e302 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractLoaderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/XmlLoaderTest.java @@ -17,7 +17,7 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// -package com.puppycrawl.tools.checkstyle.api; +package com.puppycrawl.tools.checkstyle; import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor; import static org.junit.Assert.assertEquals; @@ -35,26 +35,26 @@ import org.xml.sax.XMLReader; import com.sun.org.apache.xerces.internal.impl.Constants; -public class AbstractLoaderTest { +public class XmlLoaderTest { private static final String NAMESPACES_FEATURE = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; @Test - public void testParserConfiguratedSuccefully() throws Exception { + public void testParserConfiguredSuccessfully() throws Exception { final DummyLoader dummyLoader = new DummyLoader(new HashMap<>(1)); final XMLReader parser = Whitebox.getInternalState(dummyLoader, "parser"); assertTrue("Invalid feature state", parser.getFeature(NAMESPACES_FEATURE)); - assertEquals("Invalid entity resoler", dummyLoader, parser.getEntityResolver()); + assertEquals("Invalid entity resolver", dummyLoader, parser.getEntityResolver()); } @Test public void testIsProperUtilsClass() throws ReflectiveOperationException { assertTrue("Constructor is not private", isUtilsClassHasPrivateConstructor( - AbstractLoader.FeaturesForVerySecureJavaInstallations.class, true)); + XmlLoader.FeaturesForVerySecureJavaInstallations.class, true)); } - private static final class DummyLoader extends AbstractLoader { + private static final class DummyLoader extends XmlLoader { DummyLoader(Map<String, String> publicIdToResourceNameMap) throws SAXException, ParserConfigurationException { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java index 52788eba4..dee95b17f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java @@ -200,7 +200,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport { filesToCheck.size(), is(9)); assertThat("The path of file differs from expected", filesToCheck.get(5).getAbsolutePath(), is(getPath(FLAWLESS_INPUT))); - assertEquals("Amount of logged messages in unxexpected", + assertEquals("Amount of logged messages in unexpected", 9, antTask.getLoggedMessages().size()); } @@ -250,7 +250,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport { } @Test - public final void testNonExistingConfig() throws IOException { + public final void testNonExistentConfig() throws IOException { final CheckstyleAntTask antTask = new CheckstyleAntTask(); antTask.setConfig(getPath(NOT_EXISTING_FILE)); antTask.setProject(new Project()); @@ -491,7 +491,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport { } @Test - public final void testSetPropertiesNonExistingFile() throws IOException { + public final void testSetPropertiesNonExistentFile() throws IOException { final CheckstyleAntTask antTask = getCheckstyleAntTask(); antTask.setFile(new File(getPath(FLAWLESS_INPUT))); antTask.setProperties(new File(getPath(NOT_EXISTING_FILE))); @@ -666,7 +666,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport { Whitebox.getInternalState(antTask, "classpath")); } - /** This test is created to satisfy pitest, it is hard to emulate Referece by Id */ + /** This test is created to satisfy pitest, it is hard to emulate Reference by Id. */ @Test public void testSetClasspathRef1() { final CheckstyleAntTask antTask = new CheckstyleAntTask(); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java index 37b07b850..2e2d7a774 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java @@ -104,20 +104,20 @@ public class AbstractFileSetCheckTest { } @Test - public void testGetFileExtention() { + public void testGetFileExtension() { final DummyFileSetCheck check = new DummyFileSetCheck(); check.setFileExtensions("tmp", ".java"); - final String[] expectedExtentions = {".tmp", ".java"}; + final String[] expectedExtensions = {".tmp", ".java"}; Assert.assertArrayEquals("Invalid extensions", - expectedExtentions, check.getFileExtensions()); + expectedExtensions, check.getFileExtensions()); } /** - * This javadoc exists only to suppress Intellij Idea inspection + * This javadoc exists only to suppress Intellij Idea inspection. */ @Test - public void testSetExtentionThrowsExceptionWhenTheyAreNull() { + public void testSetExtensionThrowsExceptionWhenTheyAreNull() { final DummyFileSetCheck check = new DummyFileSetCheck(); try { check.setFileExtensions((String[]) null); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java index 7ad0be759..15e6b308c 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java @@ -42,13 +42,13 @@ public class AutomaticBeanTest { public void testConfigureNoSuchAttribute() { final TestBean testBean = new TestBean(); final DefaultConfiguration conf = new DefaultConfiguration("testConf"); - conf.addAttribute("NonExisting", "doesn't matter"); + conf.addAttribute("NonExistent", "doesn't matter"); try { testBean.configure(conf); fail("Exception is expected"); } catch (CheckstyleException ex) { - final String expected = "Property 'NonExisting' in module "; + final String expected = "Property 'NonExistent' in module "; assertNull("Exceptions cause should be null", ex.getCause()); assertTrue("Invalid exception message, should start with: " + expected, ex.getMessage().startsWith(expected)); @@ -209,5 +209,10 @@ public class AutomaticBeanTest { throw new IllegalStateException(privateField + "," + wrong + "," + val + "," + value); } + @Override + protected void finishLocalSetup() throws CheckstyleException { + // No code by default + } + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java index bf07a5be1..d3261a0a5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java @@ -258,7 +258,7 @@ public class DetailASTTest extends AbstractModuleTestSupport { } /** - * There are asserts in checkNode, but idea does not see them + * There are asserts in checkNode, but idea does not see them. * @noinspection JUnitTestMethodWithNoAssertions */ @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java index 5bd90a89b..13a874328 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java @@ -34,8 +34,6 @@ import java.util.Map; import org.junit.Test; import org.powermock.reflect.Whitebox; -import com.google.common.collect.ImmutableMap; - public class FileContentsTest { @Test @@ -101,7 +99,7 @@ public class FileContentsTest { final FileContents fileContents = new FileContents( new FileText(new File("filename"), Collections.singletonList(" // "))); fileContents.reportCComment(1, 2, 1, 2); - final ImmutableMap<Integer, List<TextBlock>> comments = fileContents.getCComments(); + final Map<Integer, List<TextBlock>> comments = fileContents.getCComments(); assertEquals("Invalid comment", new Comment(new String[] {"/"}, 2, 1, 2).toString(), @@ -158,7 +156,7 @@ public class FileContentsTest { new FileText(new File("filename"), Arrays.asList(" ", " ", " /* test ", " */ ", " "))); fileContents.reportCComment(3, 2, 4, 2); - final ImmutableMap<Integer, List<TextBlock>> blockComments = + final Map<Integer, List<TextBlock>> blockComments = fileContents.getBlockComments(); final String[] text = blockComments.get(3).get(0).getText(); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java index af5d93cf8..7918d9683 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java @@ -38,11 +38,11 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.google.common.io.Closeables; import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; @RunWith(PowerMockRunner.class) -@PrepareForTest(Closeables.class) +@PrepareForTest(CommonUtils.class) public class FileTextTest extends AbstractPathTestSupport { @Override protected String getPackageLocation() { @@ -67,9 +67,9 @@ public class FileTextTest extends AbstractPathTestSupport { @Test public void testSupportedCharset() throws IOException { //check if reader finally closed - mockStatic(Closeables.class); - doNothing().when(Closeables.class); - Closeables.closeQuietly(any(Reader.class)); + mockStatic(CommonUtils.class); + doNothing().when(CommonUtils.class); + CommonUtils.close(any(Reader.class)); final String charsetName = StandardCharsets.ISO_8859_1.name(); final FileText fileText = new FileText(new File(getPath("InputFileTextImportControl.xml")), @@ -77,7 +77,7 @@ public class FileTextTest extends AbstractPathTestSupport { assertEquals("Invalid charset name", charsetName, fileText.getCharset().name()); verifyStatic(times(2)); - Closeables.closeQuietly(any(Reader.class)); + CommonUtils.close(any(Reader.class)); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java index d66e43619..73dc5decb 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.filters.SeverityMatchFilter; import nl.jqno.equalsverifier.EqualsVerifier; -/** Tests SuppressElementFilter. */ public class FilterSetTest { @Test public void testEqualsAndHashCode() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java index d930caa79..f77c8cbae 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java @@ -80,7 +80,7 @@ public class NewlineAtEndOfFileCheckTest /** * Pitest requires all closes of streams and readers to be verified. Using PowerMock - * is almost only posibility to check it without rewriting production code. + * is almost only possibility to check it without rewriting production code. * * @throws Exception when code tested throws some exception */ @@ -230,7 +230,7 @@ public class NewlineAtEndOfFileCheckTest final File impossibleFile = new File(""); final FileText fileText = new FileText(impossibleFile, lines); final Set<LocalizedMessage> messages = check.process(impossibleFile, fileText); - assertEquals("Ammount of messages is unexpected", + assertEquals("Amount of messages is unexpected", 1, messages.size()); final Iterator<LocalizedMessage> iterator = messages.iterator(); assertEquals("Violation message differs from expected", diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java index 25640caa5..a594c3db5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java @@ -85,9 +85,9 @@ public class SuppressWarningsHolderTest extends AbstractModuleTestSupport { @Test public void testGetDefaultAlias() { - assertEquals("Diffault alias differs from expected", + assertEquals("Default alias differs from expected", "somename", SuppressWarningsHolder.getDefaultAlias("SomeName")); - assertEquals("Diffault alias differs from expected", + assertEquals("Default alias differs from expected", "somename", SuppressWarningsHolder.getDefaultAlias("SomeNameCheck")); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java index 2aafd1e76..c1b6aecdc 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java @@ -80,6 +80,27 @@ public class TrailingCommentCheckTest extends AbstractModuleTestSupport { } @Test + public void testFormat() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(TrailingCommentCheck.class); + checkConfig.addAttribute("format", "NOT MATCH"); + final String[] expected = { + "4: " + getCheckMessage(MSG_KEY), + "5: " + getCheckMessage(MSG_KEY), + "6: " + getCheckMessage(MSG_KEY), + "7: " + getCheckMessage(MSG_KEY), + "8: " + getCheckMessage(MSG_KEY), + "13: " + getCheckMessage(MSG_KEY), + "14: " + getCheckMessage(MSG_KEY), + "15: " + getCheckMessage(MSG_KEY), + "18: " + getCheckMessage(MSG_KEY), + "19: " + getCheckMessage(MSG_KEY), + "26: " + getCheckMessage(MSG_KEY), + "29: " + getCheckMessage(MSG_KEY), + }; + verify(checkConfig, getPath("InputTrailingComment.java"), expected); + } + + @Test public void testCallVisitToken() { final TrailingCommentCheck check = new TrailingCommentCheck(); try { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java index 408ec6fbb..9395843bd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java @@ -57,7 +57,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import com.google.common.collect.ImmutableMap; import com.google.common.io.Closeables; -import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.AbstractXmlTestSupport; import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.XMLLogger; @@ -68,11 +68,12 @@ import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.MessageDispatcher; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.SeverityLevelCounter; +import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; @RunWith(PowerMockRunner.class) @PrepareForTest(Closeables.class) -public class TranslationCheckTest extends AbstractModuleTestSupport { +public class TranslationCheckTest extends AbstractXmlTestSupport { @Captor private ArgumentCaptor<SortedSet<LocalizedMessage>> captor; @@ -144,6 +145,7 @@ public class TranslationCheckTest extends AbstractModuleTestSupport { checkConfig.addAttribute("requiredTranslations", "ja,de"); checkConfig.addAttribute("baseName", "^InputTranslation.*$"); final Checker checker = createChecker(checkConfig); + checker.setBasedir(getPath("")); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final XMLLogger logger = new XMLLogger(out, AutomaticBean.OutputStreamOptions.NONE); checker.addListener(logger); @@ -162,8 +164,21 @@ public class TranslationCheckTest extends AbstractModuleTestSupport { final String secondErrorMessage = getCheckMessage(MSG_KEY, "anotherKey"); verify(checker, propertyFiles, ImmutableMap.of( - getPath(""), Collections.singletonList(line + firstErrorMessage), - translationProps, Collections.singletonList(line + secondErrorMessage))); + ":0", Collections.singletonList(" " + firstErrorMessage), + "InputTranslationCheckFireErrors_de.properties", + Collections.singletonList(line + secondErrorMessage))); + + verifyXml(getPath("ExpectedTranslationLog.xml"), out, (expected, actual) -> { + // order is not always maintained here for an unknown reason. + // File names can appear in different orders depending on the OS and VM. + // This ensures we pick up the correct file based on its name and the + // number of children it has. + return !"file".equals(expected.getNodeName()) + || expected.getAttributes().getNamedItem("name").getNodeValue() + .equals(actual.getAttributes().getNamedItem("name").getNodeValue()) + && XmlUtil.getChildrenElements(expected).size() == XmlUtil + .getChildrenElements(actual).size(); + }, firstErrorMessage, secondErrorMessage); } @Test @@ -369,7 +384,7 @@ public class TranslationCheckTest extends AbstractModuleTestSupport { /** * Pitest requires all closes of streams and readers to be verified. Using PowerMock - * is almost only posibility to check it without rewriting production code. + * is almost only possibility to check it without rewriting production code. * * @throws Exception when code tested throws some exception */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java index 4af491695..65bf7e6be 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java @@ -54,9 +54,6 @@ import com.puppycrawl.tools.checkstyle.api.FileText; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -/** - * JUnit tests for Unique Properties check. - */ @RunWith(PowerMockRunner.class) @PrepareForTest(Closeables.class) public class UniquePropertiesCheckTest extends AbstractModuleTestSupport { @@ -95,7 +92,7 @@ public class UniquePropertiesCheckTest extends AbstractModuleTestSupport { /** * Pitest requires all closes of streams and readers to be verified. Using PowerMock - * is almost only posibility to check it without rewriting production code. + * is almost only possibility to check it without rewriting production code. * * @throws Exception when code tested throws some exception */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java index de62224a9..9934f904e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java @@ -28,11 +28,6 @@ import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.TokenTypes; -/** - * - * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a> - * - */ public class EmptyCatchBlockCheckTest extends AbstractModuleTestSupport { @Override protected String getPackageLocation() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java index 2a087202e..c19a4de62 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java @@ -72,7 +72,7 @@ public class ExplicitInitializationCheckTest extends AbstractModuleTestSupport { } @Test - public void testonlyObjectReferences() throws Exception { + public void testOnlyObjectReferences() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ExplicitInitializationCheck.class); checkConfig.addAttribute("onlyObjectReferences", "true"); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java index 78113a128..d35d92871 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java @@ -53,7 +53,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport { "424:9: " + getCheckMessage(MSG_FALL_THROUGH), "436:9: " + getCheckMessage(MSG_FALL_THROUGH), "446:9: " + getCheckMessage(MSG_FALL_THROUGH), - + "555:9: " + getCheckMessage(MSG_FALL_THROUGH), + "556:9: " + getCheckMessage(MSG_FALL_THROUGH), + "557:9: " + getCheckMessage(MSG_FALL_THROUGH), }; verify(checkConfig, getPath("InputFallThrough.java"), @@ -82,6 +84,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport { "424:9: " + getCheckMessage(MSG_FALL_THROUGH), "436:9: " + getCheckMessage(MSG_FALL_THROUGH), "446:9: " + getCheckMessage(MSG_FALL_THROUGH), + "555:9: " + getCheckMessage(MSG_FALL_THROUGH), + "556:9: " + getCheckMessage(MSG_FALL_THROUGH), + "557:9: " + getCheckMessage(MSG_FALL_THROUGH), }; verify(checkConfig, getPath("InputFallThrough.java"), @@ -133,6 +138,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport { "507:9: " + getCheckMessage(MSG_FALL_THROUGH), "514:9: " + getCheckMessage(MSG_FALL_THROUGH), "546:12: " + getCheckMessage(MSG_FALL_THROUGH), + "555:9: " + getCheckMessage(MSG_FALL_THROUGH), + "556:9: " + getCheckMessage(MSG_FALL_THROUGH), + "557:9: " + getCheckMessage(MSG_FALL_THROUGH), }; verify(checkConfig, getPath("InputFallThrough.java"), diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java index a18cfb6f9..6898432dd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java @@ -23,6 +23,7 @@ import static com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextChec import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Test; @@ -30,6 +31,7 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; import com.puppycrawl.tools.checkstyle.utils.TokenUtils; public class IllegalTokenTextCheckTest @@ -123,6 +125,19 @@ public class IllegalTokenTextCheckTest } @Test + public void testOrderOfProperties() throws Exception { + // pure class must be used as configuration doesn't guarantee order of + // attributes + final IllegalTokenTextCheck check = new IllegalTokenTextCheck(); + check.setFormat("test"); + check.setIgnoreCase(true); + final Pattern actual = (Pattern) TestUtil.getClassDeclaredField( + IllegalTokenTextCheck.class, "regexp").get(check); + Assert.assertEquals("should match", Pattern.CASE_INSENSITIVE, actual.flags()); + Assert.assertEquals("should match", "test", actual.pattern()); + } + + @Test public void testAcceptableTokensMakeSense() { final int expectedTokenTypesTotalNumber = 169; Assert.assertEquals("Total number of TokenTypes has changed, acceptable tokens in" diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java index ee10c281b..59fa28159 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java @@ -82,6 +82,7 @@ public class IllegalTypeCheckTest extends AbstractModuleTestSupport { "com.puppycrawl.tools.checkstyle.checks.coding.illegaltype." + "InputIllegalType.AbstractClass"), "16:13: " + getCheckMessage(MSG_KEY, "java.util.TreeSet"), + "25:36: " + getCheckMessage(MSG_KEY, "java.util.TreeSet"), }; verify(checkConfig, getPath("InputIllegalType.java"), expected); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java index 2d891ff93..b5b851fd6 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java @@ -57,6 +57,7 @@ public class ModifiedControlVariableCheckTest "56:14: " + getCheckMessage(MSG_KEY, "m"), "67:15: " + getCheckMessage(MSG_KEY, "i"), "68:15: " + getCheckMessage(MSG_KEY, "k"), + "78:15: " + getCheckMessage(MSG_KEY, "v"), }; verify(checkConfig, getPath("InputModifiedControlVariableBothForLoops.java"), expected); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java index 41caf8415..fc537abef 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java @@ -46,6 +46,9 @@ public class MultipleVariableDeclarationsCheckTest extends AbstractModuleTestSup "9:9: " + getCheckMessage(MSG_MULTIPLE), "13:5: " + getCheckMessage(MSG_MULTIPLE), "16:5: " + getCheckMessage(MSG_MULTIPLE), + "35:9: " + getCheckMessage(MSG_MULTIPLE), + "35:31: " + getCheckMessage(MSG_MULTIPLE), + "35:44: " + getCheckMessage(MSG_MULTIPLE), }; verify(checkConfig, diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java index 5ca5221a1..04cd3e5e5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java @@ -28,10 +28,6 @@ import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -/** - * The unit-test for the {@code NestedForDepthCheck}-checkstyle enhancement. - * @see NestedForDepthCheck - */ public class NestedForDepthCheckTest extends AbstractModuleTestSupport { @Override protected String getPackageLocation() { @@ -56,6 +52,7 @@ public class NestedForDepthCheckTest extends AbstractModuleTestSupport { final String[] expected = { "43:11: " + getCheckMessage(MSG_KEY, 3, 2), "44:13: " + getCheckMessage(MSG_KEY, 4, 2), + "47:13: " + getCheckMessage(MSG_KEY, 4, 2), }; verify(checkConfig, getPath("InputNestedForDepth.java"), diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java index 89df6c04e..5aae2c10d 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java @@ -27,9 +27,6 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -/** - * NoCloneCheck test. - */ public class NoCloneCheckTest extends AbstractModuleTestSupport { @Override diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java index 48fe46337..83b7dac17 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java @@ -22,6 +22,7 @@ package com.puppycrawl.tools.checkstyle.checks.coding; import static com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.MSG_METHOD; import static com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.MSG_VARIABLE; +import java.lang.reflect.Constructor; import java.util.SortedSet; import org.junit.Assert; @@ -33,6 +34,7 @@ import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; public class RequireThisCheckTest extends AbstractModuleTestSupport { @@ -58,6 +60,11 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport { "121:13: " + getCheckMessage(MSG_METHOD, "instanceMethod", "Issue2240."), "122:13: " + getCheckMessage(MSG_VARIABLE, "i", "Issue2240."), "134:9: " + getCheckMessage(MSG_METHOD, "foo", ""), + "142:9: " + getCheckMessage(MSG_VARIABLE, "s", ""), + "168:16: " + getCheckMessage(MSG_VARIABLE, "a", ""), + "168:20: " + getCheckMessage(MSG_VARIABLE, "a", ""), + "174:16: " + getCheckMessage(MSG_VARIABLE, "b", ""), + "174:20: " + getCheckMessage(MSG_VARIABLE, "b", ""), }; verify(checkConfig, getPath("InputRequireThisEnumInnerClassesAndBugs.java"), @@ -95,6 +102,11 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport { "113:9: " + getCheckMessage(MSG_VARIABLE, "i", ""), "114:9: " + getCheckMessage(MSG_VARIABLE, "i", ""), "122:13: " + getCheckMessage(MSG_VARIABLE, "i", "Issue2240."), + "142:9: " + getCheckMessage(MSG_VARIABLE, "s", ""), + "168:16: " + getCheckMessage(MSG_VARIABLE, "a", ""), + "168:20: " + getCheckMessage(MSG_VARIABLE, "a", ""), + "174:16: " + getCheckMessage(MSG_VARIABLE, "b", ""), + "174:20: " + getCheckMessage(MSG_VARIABLE, "b", ""), }; verify(checkConfig, getPath("InputRequireThisEnumInnerClassesAndBugs.java"), @@ -260,7 +272,7 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport { final String[] expected = { "15:9: " + getCheckMessage(MSG_VARIABLE, "tags", ""), }; - verify(checkConfig, getPath("InputRequireThisMetodReferences.java"), expected); + verify(checkConfig, getPath("InputRequireThisMethodReferences.java"), expected); } @Test @@ -294,6 +306,43 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport { } @Test + public void testCatchVariables() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class); + checkConfig.addAttribute("validateOnlyOverlapping", "false"); + final String[] expected = { + "29:21: " + getCheckMessage(MSG_VARIABLE, "ex", ""), + }; + verify(checkConfig, getPath("InputRequireThisCatchVariables.java"), expected); + } + + @Test + public void testEnumConstant() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class); + checkConfig.addAttribute("validateOnlyOverlapping", "false"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputRequireThisEnumConstant.java"), expected); + } + + @Test + public void testAnnotationInterface() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class); + checkConfig.addAttribute("validateOnlyOverlapping", "false"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, getPath("InputRequireThisAnnotationInterface.java"), expected); + } + + @Test + public void testFor() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class); + checkConfig.addAttribute("validateOnlyOverlapping", "false"); + final String[] expected = { + "13:13: " + getCheckMessage(MSG_VARIABLE, "bottom", ""), + "21:34: " + getCheckMessage(MSG_VARIABLE, "name", ""), + }; + verify(checkConfig, getPath("InputRequireThisFor.java"), expected); + } + + @Test public void test() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; @@ -307,4 +356,18 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport { final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputRequireThisExtendedMethod.java"), expected); } + + @Test + public void testUnusedMethod() throws Exception { + final DetailAST ident = new DetailAST(); + ident.setText("testName"); + + final Class<?> cls = Class.forName(RequireThisCheck.class.getName() + "$CatchFrame"); + final Constructor<?> constructor = cls.getDeclaredConstructors()[0]; + constructor.setAccessible(true); + final Object o = constructor.newInstance(null, ident); + + Assert.assertEquals("expected ident token", ident, + TestUtil.getClassDeclaredMethod(cls, "getFrameNameIdent").invoke(o)); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java index eccf7ec67..6e407a47f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java @@ -20,6 +20,7 @@ package com.puppycrawl.tools.checkstyle.checks.coding; import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY; +import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY_VOID; import static org.junit.Assert.assertTrue; import java.io.File; @@ -48,9 +49,9 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport { final DefaultConfiguration checkConfig = createModuleConfig(ReturnCountCheck.class); final String[] expected = { - "18:5: " + getCheckMessage(MSG_KEY, 7, 1), - "30:5: " + getCheckMessage(MSG_KEY, 2, 1), - "35:17: " + getCheckMessage(MSG_KEY, 6, 1), + "18:5: " + getCheckMessage(MSG_KEY_VOID, 7, 1), + "30:5: " + getCheckMessage(MSG_KEY_VOID, 2, 1), + "35:17: " + getCheckMessage(MSG_KEY_VOID, 6, 1), "49:5: " + getCheckMessage(MSG_KEY, 7, 2), }; verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected); @@ -63,9 +64,9 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport { checkConfig.addAttribute("format", "^$"); final String[] expected = { "5:5: " + getCheckMessage(MSG_KEY, 7, 2), - "18:5: " + getCheckMessage(MSG_KEY, 7, 1), - "30:5: " + getCheckMessage(MSG_KEY, 2, 1), - "35:17: " + getCheckMessage(MSG_KEY, 6, 1), + "18:5: " + getCheckMessage(MSG_KEY_VOID, 7, 1), + "30:5: " + getCheckMessage(MSG_KEY_VOID, 2, 1), + "35:17: " + getCheckMessage(MSG_KEY_VOID, 6, 1), "49:5: " + getCheckMessage(MSG_KEY, 7, 2), }; verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected); @@ -146,10 +147,11 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport { checkConfig.addAttribute("max", "2"); checkConfig.addAttribute("maxForVoid", "0"); final String[] expected = { - "4:5: " + getCheckMessage(MSG_KEY, 1, 0), - "8:5: " + getCheckMessage(MSG_KEY, 1, 0), - "14:5: " + getCheckMessage(MSG_KEY, 2, 0), + "4:5: " + getCheckMessage(MSG_KEY_VOID, 1, 0), + "8:5: " + getCheckMessage(MSG_KEY_VOID, 1, 0), + "14:5: " + getCheckMessage(MSG_KEY_VOID, 2, 0), "30:5: " + getCheckMessage(MSG_KEY, 3, 2), + "41:5: " + getCheckMessage(MSG_KEY_VOID, 2, 0), }; verify(checkConfig, getPath("InputReturnCountVoid.java"), expected); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java index 07de21709..038eaf22c 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java @@ -95,6 +95,8 @@ public class UnnecessaryParenthesesCheckTest extends AbstractModuleTestSupport { "81:11: " + getCheckMessage(MSG_ASSIGN), "81:16: " + getCheckMessage(MSG_LITERAL, "3"), "82:39: " + getCheckMessage(MSG_ASSIGN), + "93:11: " + getCheckMessage(MSG_ASSIGN), + "93:14: " + getCheckMessage(MSG_STRING, "\"12345678901234567890123\""), }; verify(checkConfig, getPath("InputUnnecessaryParenthesesOperatorsAndCasts.java"), expected); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java index 7e17610eb..5e54ba784 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java @@ -27,6 +27,7 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; public class VariableDeclarationUsageDistanceCheckTest extends AbstractModuleTestSupport { @@ -76,6 +77,7 @@ public class VariableDeclarationUsageDistanceCheckTest extends "891: " + getCheckMessage(MSG_KEY, "a", 4, 1), "901: " + getCheckMessage(MSG_KEY, "a", 4, 1), "967: " + getCheckMessage(MSG_KEY, "a", 4, 1), + "978: " + getCheckMessage(MSG_KEY, "a", 2, 1), }; verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected); } @@ -170,6 +172,7 @@ public class VariableDeclarationUsageDistanceCheckTest extends "505: " + getCheckMessage(MSG_KEY, "files", 2, 1), "540: " + getCheckMessage(MSG_KEY, "id", 2, 1), "542: " + getCheckMessage(MSG_KEY, "parentId", 4, 1), + "978: " + getCheckMessage(MSG_KEY, "a", 2, 1), }; verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected); } @@ -239,7 +242,27 @@ public class VariableDeclarationUsageDistanceCheckTest extends "542: " + getCheckMessage(MSG_KEY_EXT, "parentId", 4, 3), }; - createChecker(checkConfig); verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected); } + + @Test + public void testAnonymousClass() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(VariableDeclarationUsageDistanceCheck.class); + final String[] expected = { + "9: " + getCheckMessage(MSG_KEY_EXT, "prefs", 4, 3), + }; + + verify(checkConfig, getPath("InputVariableDeclarationUsageDistanceAnonymous.java"), + expected); + } + + @Test + public void testLabels() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(VariableDeclarationUsageDistanceCheck.class); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + + verify(checkConfig, getPath("InputVariableDeclarationUsageDistanceLabels.java"), expected); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java index 435c53088..29798691f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java @@ -114,6 +114,6 @@ public class ThrowsCountCheckTest extends AbstractModuleTestSupport { final String[] expected = { "18:26: " + getCheckMessage(MSG_KEY, 5, 4), }; - verify(checkConfig, getPath("InputThrowsCountMwthodWithAnnotation.java"), expected); + verify(checkConfig, getPath("InputThrowsCountMethodWithAnnotation.java"), expected); } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java index 571f9fac6..eab6ec9cc 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java @@ -450,7 +450,7 @@ public class VisibilityModifierCheckTest * class with name "", but in this case internal collection will have short names * as "" that will not make problems, but will be weird in debug. * - * @throws Exception when exception occured during execution. + * @throws Exception when exception occurred during execution. */ @Test public void testIsStarImportNullAst() throws Exception { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java index 8db53f01d..f82d75a2b 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java @@ -88,9 +88,9 @@ public class HeaderCheckTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingHeaderFile() throws Exception { + public void testNonExistentHeaderFile() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); - checkConfig.addAttribute("headerFile", getPath("nonExisting.file")); + checkConfig.addAttribute("headerFile", getPath("nonExistent.file")); try { createChecker(checkConfig); fail("CheckstyleException is expected"); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java index 7ef2abd28..aae83138b 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java @@ -48,6 +48,6 @@ public class AccessResultTest { AccessResult.DISALLOWED, AccessResult.UNKNOWN, }; - assertArrayEquals("Invalid aaccess result values", expected, actual); + assertArrayEquals("Invalid access result values", expected, actual); } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java index 29759138f..1aa1e08d6 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java @@ -29,11 +29,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; import java.lang.reflect.Method; import org.junit.Test; import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.Checker; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.DetailAST; @@ -336,6 +338,59 @@ public class CustomImportOrderCheckTest extends AbstractModuleTestSupport { } @Test + public void testCompareImports() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CustomImportOrderCheck.class); + checkConfig.addAttribute("specialImportsRegExp", "com"); + checkConfig.addAttribute("sortImportsInGroupAlphabetically", "true"); + checkConfig.addAttribute("customImportOrderRules", + "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS"); + final String[] expected = { + "4: " + getCheckMessage(MSG_LEX, "java.util.Map", + "java.util.Map.Entry"), + }; + + verify(checkConfig, getPath("InputCustomImportOrderCompareImports.java"), expected); + } + + @Test + public void testFindBetterPatternMatch() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CustomImportOrderCheck.class); + checkConfig.addAttribute("standardPackageRegExp", "java|javax|event.*"); + checkConfig.addAttribute("specialImportsRegExp", "An|lang|java|collect|event"); + checkConfig.addAttribute("thirdPartyPackageRegExp", "com"); + checkConfig.addAttribute("separateLineBetweenGroups", "true"); + checkConfig.addAttribute("customImportOrderRules", + "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE"); + final String[] expected = { + "8: " + getCheckMessage(MSG_ORDER, THIRD, SPECIAL, + "com.google.common.annotations.Beta"), + }; + + verify(checkConfig, getPath("InputCustomImportOrderFindBetterPatternMatch.java"), expected); + } + + @Test + public void testBeginTreeClear() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(CustomImportOrderCheck.class); + checkConfig.addAttribute("specialImportsRegExp", "com"); + checkConfig.addAttribute("separateLineBetweenGroups", "false"); + checkConfig.addAttribute("customImportOrderRules", + "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + final Checker checker = createChecker(checkConfig); + final String fileName1 = getPath("InputCustomImportOrderImportsContainingJava.java"); + final String fileName2 = getPath("InputCustomImportOrderNoValid.java"); + final File[] files = { + new File(fileName1), + new File(fileName2), + }; + verify(checker, files, fileName1, expected); + } + + @Test public void testImportsContainingJava() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(CustomImportOrderCheck.class); checkConfig.addAttribute("customImportOrderRules", diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java index 902dcbf87..dd4491656 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java @@ -112,7 +112,7 @@ public class IllegalImportCheckTest extends AbstractModuleTestSupport { } @Test - public void testIllegalClassessRegularExpression() + public void testIllegalClassesRegularExpression() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(IllegalImportCheck.class); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java index 5fab0d1a8..6cd86d2a7 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java @@ -349,7 +349,7 @@ public class ImportControlCheckTest extends AbstractModuleTestSupport { // One more time to use cache. verify(checkerConfig, filePath, expected); - assertTrue("External resourse is not present in cache", + assertTrue("External resource is not present in cache", new String(Files.readAllBytes(cacheFile.toPath()), StandardCharsets.UTF_8).contains("InputImportControlOneRegExp.xml")); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java index ded4f34ae..7a92cc5e5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java @@ -68,92 +68,92 @@ public class ImportControlTest { @Test public void testLocateFinest() { - assertEquals("Unxpected response", icRoot, icRoot + assertEquals("Unexpected response", icRoot, icRoot .locateFinest("com.kazgroup.courtlink.domain")); - assertEquals("Unxpected response", icCommon, icRoot + assertEquals("Unexpected response", icCommon, icRoot .locateFinest("com.kazgroup.courtlink.common.api")); - assertNull("Unxpected response", icRoot.locateFinest("com")); + assertNull("Unexpected response", icRoot.locateFinest("com")); } @Test public void testEnsureTrailingDot() { - assertNull("Unxpected response", icRoot.locateFinest("com.kazgroup.courtlinkkk")); - assertNull("Unxpected response", + assertNull("Unexpected response", icRoot.locateFinest("com.kazgroup.courtlinkkk")); + assertNull("Unexpected response", icRoot.locateFinest("com.kazgroup.courtlink/common.api")); } @Test public void testCheckAccess() { - assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( "com.kazgroup.courtlink.common", "org.springframework.something")); - assertEquals("Unxpected access result", AccessResult.ALLOWED, icCommon + assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommon .checkAccess("com.kazgroup.courtlink.common", "org.apache.commons.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( "com.kazgroup.courtlink.common", "org.apache.commons")); - assertEquals("Unxpected access result", AccessResult.ALLOWED, icCommon.checkAccess( + assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommon.checkAccess( "com.kazgroup.courtlink.common", "org.hibernate.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess( "com.kazgroup.courtlink.common", "com.badpackage.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, icRoot.checkAccess( + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icRoot.checkAccess( "com.kazgroup.courtlink", "org.hibernate.something")); } @Test public void testUnknownPkg() { - assertNull("Unxpected response", icRoot.locateFinest("net.another")); + assertNull("Unexpected response", icRoot.locateFinest("net.another")); } @Test public void testRegExpChildLocateFinest() { - assertEquals("Unxpected response", icRootRegexpChild, icRootRegexpChild + assertEquals("Unexpected response", icRootRegexpChild, icRootRegexpChild .locateFinest("com.kazgroup.courtlink.domain")); - assertEquals("Unxpected response", icCommonRegexpChild, icRootRegexpChild + assertEquals("Unexpected response", icCommonRegexpChild, icRootRegexpChild .locateFinest("com.kazgroup.courtlink.common.api")); - assertNull("Unxpected response", icRootRegexpChild.locateFinest("com")); + assertNull("Unexpected response", icRootRegexpChild.locateFinest("com")); } @Test public void testRegExpChildCheckAccess() { - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.springframework.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.luiframework.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "de.springframework.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "de.luiframework.something")); - assertEquals("Unxpected access result", AccessResult.ALLOWED, + assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.apache.commons.something")); - assertEquals("Unxpected access result", AccessResult.ALLOWED, + assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.lui.commons.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.apache.commons")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.lui.commons")); - assertEquals("Unxpected access result", AccessResult.ALLOWED, + assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "org.hibernate.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common", "com.badpackage.something")); - assertEquals("Unxpected access result", AccessResult.DISALLOWED, + assertEquals("Unexpected access result", AccessResult.DISALLOWED, icRootRegexpChild.checkAccess("com.kazgroup.courtlink", "org.hibernate.something")); } @Test public void testRegExpChildUnknownPkg() { - assertNull("Unxpected response", icRootRegexpChild.locateFinest("net.another")); + assertNull("Unexpected response", icRootRegexpChild.locateFinest("net.another")); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java index df5ab75f6..7d3322275 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java @@ -133,7 +133,7 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport { "7: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "org.junit.Assert.assertEquals"), }; - verify(checkConfig, getPath("InputImportOrderStaticGroupSeperated.java"), expected); + verify(checkConfig, getPath("InputImportOrderStaticGroupSeparated.java"), expected); } @Test @@ -409,6 +409,57 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport { } @Test + public void testStaticGroupsAlphabeticalOrderBottomNegative() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ImportOrderCheck.class); + checkConfig.addAttribute("option", "bottom"); + checkConfig.addAttribute("groups", "org, java"); + checkConfig.addAttribute("separated", "true"); + checkConfig.addAttribute("sortStaticImportsAlphabetically", "true"); + final String[] expected = { + "8: " + getCheckMessage(MSG_ORDERING, "java.util.Set"), + }; + verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative.java"), + expected); + } + + /** Tests that a non-static import after a static import correctly gives an + * error if order=bottom. */ + + @Test + public void testStaticGroupsAlphabeticalOrderTopNegative() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ImportOrderCheck.class); + checkConfig.addAttribute("option", "top"); + checkConfig.addAttribute("groups", "org, java"); + checkConfig.addAttribute("separated", "true"); + checkConfig.addAttribute("sortStaticImportsAlphabetically", "true"); + final String[] expected = { + "5: " + getCheckMessage(MSG_ORDERING, "java.lang.Math.PI"), + }; + verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative.java"), + expected); + } + + /** Tests that a non-static import before a static import correctly gives an + * error if order=top. */ + + @Test + public void testStaticGroupsAlphabeticalOrderBottomNegative2() throws Exception { + final DefaultConfiguration checkConfig = + createModuleConfig(ImportOrderCheck.class); + checkConfig.addAttribute("option", "bottom"); + checkConfig.addAttribute("groups", "org, java"); + checkConfig.addAttribute("separated", "true"); + checkConfig.addAttribute("sortStaticImportsAlphabetically", "true"); + final String[] expected = { + "8: " + getCheckMessage(MSG_ORDERING, "java.util.Set"), + }; + verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative2.java"), + expected); + } + + @Test public void testStaticGroupsOrderBottom() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); @@ -430,7 +481,7 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport { final String[] expected = { "6: " + getCheckMessage(MSG_ORDERING, "java.awt.event.ActionEvent"), }; - verify(checkConfig, getPath("InputImportOrderRepetiton.java"), expected); + verify(checkConfig, getPath("InputImportOrderRepetition.java"), expected); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java index 11e294814..4102b4512 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java @@ -31,12 +31,6 @@ import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -/** -* -* @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a> -* @author <a href="mailto:andreyselkin@gmail.com">Andrei Selkin</a> -* -*/ public class CommentsIndentationCheckTest extends AbstractModuleTestSupport { @Override @@ -221,7 +215,7 @@ public class CommentsIndentationCheckTest extends AbstractModuleTestSupport { } catch (IllegalArgumentException ex) { final String msg = ex.getMessage(); - Assert.assertEquals("Invalid excpeton message", + Assert.assertEquals("Invalid exception message", "Unexpected token type: methodStub", msg); } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java index 464a8a714..91606fe7e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java @@ -1746,6 +1746,39 @@ public class IndentationCheckTest extends AbstractModuleTestSupport { } @Test + public void testMethodPrecedeByAnnotationsWithParameterOnSeparateLine() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class); + checkConfig.addAttribute("tabWidth", "4"); + checkConfig.addAttribute("basicOffset", "2"); + checkConfig.addAttribute("braceAdjustment", "0"); + checkConfig.addAttribute("caseIndent", "2"); + checkConfig.addAttribute("throwsIndent", "4"); + checkConfig.addAttribute("lineWrappingIndentation", "4"); + checkConfig.addAttribute("arrayInitIndent", "2"); + final String fileName = + getPath("InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java"); + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(checkConfig, fileName, expected); + } + + @Test + public void testAnnotationIncorrect() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class); + checkConfig.addAttribute("tabWidth", "4"); + checkConfig.addAttribute("basicOffset", "4"); + checkConfig.addAttribute("braceAdjustment", "0"); + checkConfig.addAttribute("lineWrappingIndentation", "4"); + final String fileName = + getPath("InputIndentationAnnotationIncorrect.java"); + final String[] expected = { + "11: " + getCheckMessage(MSG_ERROR, "(", 4, 8), + "14: " + getCheckMessage(MSG_ERROR, "(", 8, 12), + "19: " + getCheckMessage(MSG_ERROR, "(", 4, 8), + }; + verify(checkConfig, fileName, expected); + } + + @Test public void testInputAnnotationScopeIndentationCheck() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class); checkConfig.addAttribute("tabWidth", "4"); @@ -1869,10 +1902,10 @@ public class IndentationCheckTest extends AbstractModuleTestSupport { * {@link IndentationCheck#MSG_CHILD_ERROR}, {@link IndentationCheck#MSG_CHILD_ERROR_MULTI}, * {@link IndentationCheck#MSG_CHILD_ERROR_MULTI} are in appropriate order. * - * In other tests, the argument 0 and text before it are chopped off and only the rest of + * <p>In other tests, the argument 0 and text before it are chopped off and only the rest of * messages are verified. Therefore, the argument 0 is required to be the first argument in * the messages above. If we update the messages in the future, it is required to keep the - * arguments in appropriate order to ensure other tests will work. + * arguments in appropriate order to ensure other tests will work.</p> * * @see IndentComment#getExpectedMessagePostfix(String) */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java index 2873e03be..40e933ce1 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java @@ -44,9 +44,8 @@ import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.DetailNode; import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes; -import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; -import com.puppycrawl.tools.checkstyle.utils.BlockCommentPosition; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; +import com.puppycrawl.tools.checkstyle.utils.JavadocUtils; public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { @@ -180,7 +179,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputAbstractJavadocPosition.java"), expected); assertEquals("Invalid number of javadocs", - 58, JavadocCatchCheck.javadocsNumber); + 65, JavadocCatchCheck.javadocsNumber); } @Test @@ -192,7 +191,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { verify(checkConfig, getPath("InputAbstractJavadocPositionWithSinglelineComments.java"), expected); assertEquals("Invalid number of javadocs", - 58, JavadocCatchCheck.javadocsNumber); + 65, JavadocCatchCheck.javadocsNumber); } @Test @@ -207,12 +206,6 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { } @Test - public void testBlockCommentPositionHasPrivateConstr() throws Exception { - Assert.assertTrue("Constructor is not private", - TestUtil.isUtilsClassHasPrivateConstructor(BlockCommentPosition.class, true)); - } - - @Test public void testTokens() { final int[] defaultJavadocTokens = {JavadocTokenTypes.JAVADOC}; final AbstractJavadocCheck check = new AbstractJavadocCheck() { @@ -231,7 +224,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { Assert.assertNotNull("Default tokens should not be null", check.getDefaultTokens()); Assert.assertArrayEquals("Acceptable tokens should be equal to default", check.getDefaultTokens(), check.getAcceptableTokens()); - Assert.assertArrayEquals("REquired tokens should be equal to default", + Assert.assertArrayEquals("Required tokens should be equal to default", check.getDefaultTokens(), check.getRequiredTokens()); Assert.assertArrayEquals("Invalid default javadoc tokens", defaultJavadocTokens, check.getDefaultJavadocTokens()); @@ -485,6 +478,9 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport { @Override public void visitJavadocToken(DetailNode ast) { assertEquals(ast.toString(), "JAVADOC", ast.getText()); + final DetailNode text = JavadocUtils.findFirstToken(ast, JavadocTokenTypes.TEXT); + Assert.assertNotNull("Empty javadoc text at " + ast, text); + assertEquals(ast.toString(), "Javadoc", text.getText()); javadocsNumber++; } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java index c4b20ee5b..15b36acac 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java @@ -150,7 +150,7 @@ public class ClassResolverTest { final String expected = "expected exception"; assertTrue("Invalid exception cause, should be: ClassNotFoundException", ex.getCause() instanceof ClassNotFoundException); - assertTrue("Invalid excpetion message, should end with: " + expected, + assertTrue("Invalid exception message, should end with: " + expected, ex.getMessage().endsWith(expected)); } } @@ -158,7 +158,7 @@ public class ClassResolverTest { /** * This test exists to prevent any possible regression and let of * https://github.com/checkstyle/checkstyle/issues/1192 to be persistent - * event is not very obvious + * event is not very obvious. * * @throws Exception when smth is not expected */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java index 1e3c28b37..8cf4210c0 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java @@ -135,8 +135,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport { "254:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "java.io.FileNotFoundException"), "256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"), "262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"), - "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING), - "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING), + "305: " + getCheckMessage(MSG_RETURN_EXPECTED), + "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"), + "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING), + "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING), }; verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected); @@ -171,8 +173,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport { "254:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "java.io.FileNotFoundException"), "256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"), "262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"), - "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING), - "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING), + "305: " + getCheckMessage(MSG_RETURN_EXPECTED), + "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"), + "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING), + "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING), }; verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected); } @@ -287,8 +291,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport { "179:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "ArrayStoreException"), "256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"), "262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"), - "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING), - "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING), + "305: " + getCheckMessage(MSG_RETURN_EXPECTED), + "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"), + "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING), + "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING), }; verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java index b197145fa..b47008fdd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java @@ -86,7 +86,7 @@ public class JavadocTagInfoTest { } ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.AUTHOR.isValidOn(ast)); } @@ -129,11 +129,11 @@ public class JavadocTagInfoTest { astParent.setType(TokenTypes.SLIST); ast.setType(TokenTypes.VARIABLE_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", tagInfo.isValidOn(ast)); ast.setType(TokenTypes.PARAMETER_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", tagInfo.isValidOn(ast)); } } @@ -166,11 +166,11 @@ public class JavadocTagInfoTest { astParent.setType(TokenTypes.SLIST); ast.setType(TokenTypes.VARIABLE_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.DEPRECATED.isValidOn(ast)); ast.setType(TokenTypes.PARAMETER_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.DEPRECATED.isValidOn(ast)); } @@ -194,11 +194,11 @@ public class JavadocTagInfoTest { astParent.setType(TokenTypes.SLIST); ast.setType(TokenTypes.VARIABLE_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL.isValidOn(ast)); ast.setType(TokenTypes.PARAMETER_DEF); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL.isValidOn(ast)); } @@ -217,7 +217,7 @@ public class JavadocTagInfoTest { } ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.EXCEPTION.isValidOn(ast)); } @@ -236,7 +236,7 @@ public class JavadocTagInfoTest { } ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.THROWS.isValidOn(ast)); } @@ -258,7 +258,7 @@ public class JavadocTagInfoTest { } ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.VERSION.isValidOn(ast)); } @@ -279,7 +279,7 @@ public class JavadocTagInfoTest { } ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.PARAM.isValidOn(ast)); } @@ -303,11 +303,11 @@ public class JavadocTagInfoTest { } astChild2.setType(TokenTypes.LITERAL_VOID); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.RETURN.isValidOn(ast)); ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.RETURN.isValidOn(ast)); } @@ -332,15 +332,15 @@ public class JavadocTagInfoTest { } astChild2.setText("1111"); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL_FIELD.isValidOn(ast)); astChild2.setType(TokenTypes.LITERAL_VOID); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL_FIELD.isValidOn(ast)); ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL_FIELD.isValidOn(ast)); } @@ -368,11 +368,11 @@ public class JavadocTagInfoTest { } astChild.setText("1111"); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL_DATA.isValidOn(ast)); ast.setType(TokenTypes.LAMBDA); - assertFalse("Should return false when ast type is invalid for currrent tag", + assertFalse("Should return false when ast type is invalid for current tag", JavadocTagInfo.SERIAL_DATA.isValidOn(ast)); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java index 76d9142a3..73815fdb2 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java @@ -34,9 +34,6 @@ import com.puppycrawl.tools.checkstyle.api.Scope; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.CommonUtils; -/** - * @author Oliver.Burn - */ public class JavadocTypeCheckTest extends AbstractModuleTestSupport { @Override protected String getPackageLocation() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java index 3bf65b75c..df90f72ca 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java @@ -82,6 +82,7 @@ public class NonEmptyAtclauseDescriptionCheckTest "91: " + getCheckMessage(MSG_KEY), "92: " + getCheckMessage(MSG_KEY), "93: " + getCheckMessage(MSG_KEY), + "120: " + getCheckMessage(MSG_KEY), }; verify(checkConfig, getPath("InputNonEmptyAtclauseDescription.java"), expected); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java index e24943492..0e8801e1d 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java @@ -28,9 +28,6 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; -/** - * Tests BlockTagUtils. - */ public class BlockTagUtilsTest { @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java index 3f29816fb..73cfff09c 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java @@ -29,9 +29,6 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; -/** - * Tests InlineTagUtils - */ public class InlineTagUtilsTest { @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java index a749d18b8..bd5832945 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java @@ -45,9 +45,10 @@ public class BooleanExpressionComplexityCheckTest extends AbstractModuleTestSupp final String[] expected = { "13:9: " + getCheckMessage(MSG_KEY, 4, 3), - "32:9: " + getCheckMessage(MSG_KEY, 6, 3), - "38:34: " + getCheckMessage(MSG_KEY, 4, 3), - "40:34: " + getCheckMessage(MSG_KEY, 4, 3), + "29:99: " + getCheckMessage(MSG_KEY, 4, 3), + "39:9: " + getCheckMessage(MSG_KEY, 6, 3), + "45:34: " + getCheckMessage(MSG_KEY, 4, 3), + "47:34: " + getCheckMessage(MSG_KEY, 4, 3), }; verify(checkConfig, getPath("InputBooleanExpressionComplexity.java"), expected); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java index e141d0987..05b80d379 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java @@ -20,7 +20,9 @@ package com.puppycrawl.tools.checkstyle.checks.metrics; import static com.puppycrawl.tools.checkstyle.checks.metrics.ClassDataAbstractionCouplingCheck.MSG_KEY; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -41,6 +43,17 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup } @Test + public void testTokens() { + final ClassDataAbstractionCouplingCheck check = new ClassDataAbstractionCouplingCheck(); + assertNotNull("Required tokens should not be null", check.getRequiredTokens()); + assertNotNull("Acceptable tokens should not be null", check.getAcceptableTokens()); + assertArrayEquals("Invalid default tokens", check.getDefaultTokens(), + check.getAcceptableTokens()); + assertArrayEquals("Invalid acceptable tokens", check.getDefaultTokens(), + check.getRequiredTokens()); + } + + @Test public void test() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ClassDataAbstractionCouplingCheck.class); @@ -58,7 +71,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup } @Test - public void testExludedPackageDirectPackages() throws Exception { + public void testExcludedPackageDirectPackages() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ClassDataAbstractionCouplingCheck.class); @@ -78,7 +91,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup } @Test - public void testExludedPackageCommonPackages() throws Exception { + public void testExcludedPackageCommonPackages() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ClassDataAbstractionCouplingCheck.class); @@ -97,7 +110,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup } @Test - public void testExludedPackageWithEndingDot() throws Exception { + public void testExcludedPackageWithEndingDot() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ClassDataAbstractionCouplingCheck.class); @@ -123,7 +136,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup } @Test - public void testExludedPackageCommonPackagesAllIgnored() throws Exception { + public void testExcludedPackageCommonPackagesAllIgnored() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ClassDataAbstractionCouplingCheck.class); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java index 9508e1f03..32cebea33 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java @@ -217,4 +217,15 @@ public class ClassFanOutComplexityCheckTest extends AbstractModuleTestSupport { verify(moduleConfig, getPath("InputClassFanOutComplexityMultiDimensionalArray.java"), expected); } + + @Test + public void testPackageName() throws Exception { + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassFanOutComplexityCheck.class); + moduleConfig.addAttribute("max", "0"); + + final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; + verify(moduleConfig, + getPath("InputClassFanOutComplexityPackageName.java"), expected); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java index b72b3f6b7..ed1373b97 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java @@ -21,7 +21,9 @@ package com.puppycrawl.tools.checkstyle.checks.metrics; import static com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck.MSG_KEY; +import java.io.File; import java.util.Collection; +import java.util.Optional; import java.util.SortedSet; import org.junit.Assert; @@ -60,6 +62,9 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport { "76:5: " + getCheckMessage(MSG_KEY, 3, 0), "88:5: " + getCheckMessage(MSG_KEY, 3, 0), "104:13: " + getCheckMessage(MSG_KEY, 2, 0), + "113:5: " + getCheckMessage(MSG_KEY, 48, 0), + "123:5: " + getCheckMessage(MSG_KEY, 1, 0), + "124:5: " + getCheckMessage(MSG_KEY, 1, 0), }; verify(checkConfig, getPath("InputNPathComplexityDefault.java"), expected); @@ -139,6 +144,35 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport { } @Test + public void testStatefulFieldsClearedOnBeginTree3() throws Exception { + final NPathComplexityCheck check = new NPathComplexityCheck(); + final Optional<DetailAST> question = TestUtil.findTokenInAstByPredicate( + TestUtil.parseFile(new File(getPath("InputNPathComplexity.java"))), + ast -> ast.getType() == TokenTypes.QUESTION); + + Assert.assertTrue("Ast should contain QUESTION", question.isPresent()); + + Assert.assertTrue("State is not cleared on beginTree", + TestUtil.isStatefulFieldClearedDuringBeginTree( + check, + question.get(), + "processingTokenEnd", + processingTokenEnd -> { + try { + return (Integer) TestUtil.getClassDeclaredField( + processingTokenEnd.getClass(), "endLineNo").get( + processingTokenEnd) == 0 + && (Integer) TestUtil.getClassDeclaredField( + processingTokenEnd.getClass(), "endColumnNo").get( + processingTokenEnd) == 0; + } + catch (IllegalAccessException | NoSuchFieldException ex) { + throw new IllegalStateException(ex); + } + })); + } + + @Test public void testDefaultConfiguration() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(NPathComplexityCheck.class); @@ -217,6 +251,31 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport { Assert.assertEquals("No exception messages expected", 0, messages2.size()); } + /** + * This must be a reflection test as it is too difficult to hit normally and + * the responsible code can't be removed without failing tests. + * TokenEnd is only used for processingTokenEnd and it is only set during visitConditional + * and visitUnitaryOperator. For it to be the same line/column, it must be the exact same + * token or a token who has the same line/column as it's child and we visit. We never + * visit the same token twice and we are only visiting on very specific tokens. + * The line can't be removed or reworked as other tests fail, and regression shows us no + * use cases to create a UT for. + * @throws Exception if there is an error. + */ + @Test + public void testTokenEndIsAfterSameLineColumn() throws Exception { + final NPathComplexityCheck check = new NPathComplexityCheck(); + final Object tokenEnd = TestUtil.getClassDeclaredField(NPathComplexityCheck.class, + "processingTokenEnd").get(check); + final DetailAST token = new DetailAST(); + token.setLineNo(0); + token.setColumnNo(0); + + Assert.assertTrue("isAfter must be true for same line/column", + (Boolean) TestUtil.getClassDeclaredMethod(tokenEnd.getClass(), "isAfter") + .invoke(tokenEnd, token)); + } + @Test public void testVisitTokenBeforeExpressionRange() { // Create first ast diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java index 4d90731cd..53405d583 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java @@ -232,6 +232,16 @@ public class RedundantModifierCheckTest } @Test + public void testEnumStaticMethodsInPublicClass() throws Exception { + final DefaultConfiguration checkConfig = createModuleConfig(RedundantModifierCheck.class); + final String[] expected = { + "12:23: " + getCheckMessage(MSG_KEY, "final"), + }; + verify(checkConfig, + getPath("InputRedundantModifierFinalInEnumStaticMethods.java"), expected); + } + + @Test public void testAnnotationOnEnumConstructor() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(RedundantModifierCheck.class); final String[] expected = { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java index ac890d336..e23bd7129 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java @@ -130,7 +130,7 @@ public class AbstractClassNameCheckTest extends AbstractModuleTestSupport { final int[] expected = { TokenTypes.CLASS_DEF, }; - Assert.assertArrayEquals("Invalid accaptable tokens", expected, actual); + Assert.assertArrayEquals("Invalid acceptable tokens", expected, actual); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java index d0b9617a2..851c15c38 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java @@ -81,8 +81,8 @@ public class MethodNameCheckTest "InputMethodNameEqualClassName", pattern), "47:9: " + getCheckMessage(MSG_KEY, "SweetInterface"), "47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern), - "53:17: " + getCheckMessage(MSG_KEY, "Outter"), - "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern), + "53:17: " + getCheckMessage(MSG_KEY, "Outer"), + "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern), }; verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected); @@ -109,7 +109,7 @@ public class MethodNameCheckTest "37:24: " + getCheckMessage(MSG_INVALID_PATTERN, "InputMethodNameEqualClassName", pattern), "47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern), - "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern), + "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern), }; verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected); @@ -137,7 +137,7 @@ public class MethodNameCheckTest "37:24: " + getCheckMessage(MSG_INVALID_PATTERN, "InputMethodNameEqualClassName", pattern), "47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern), - "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern), + "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern), }; verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected); @@ -165,7 +165,7 @@ public class MethodNameCheckTest "20:20: " + getCheckMessage(MSG_INVALID_PATTERN, "PROTECTEDfoo", pattern), }; - verify(checkConfig, getPath("InputMethodNameOverridenMethods.java"), expected); + verify(checkConfig, getPath("InputMethodNameOverriddenMethods.java"), expected); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java index 96875fba4..8b77df609 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java @@ -58,6 +58,7 @@ public class NoWhitespaceAfterCheckTest "289:6: " + getCheckMessage(MSG_KEY, "@"), "290:6: " + getCheckMessage(MSG_KEY, "@"), "291:6: " + getCheckMessage(MSG_KEY, "@"), + "296:27: " + getCheckMessage(MSG_KEY, "int"), }; verify(checkConfig, getPath("InputNoWhitespaceAfter.java"), expected); } @@ -107,7 +108,7 @@ public class NoWhitespaceAfterCheckTest "39:11: " + getCheckMessage(MSG_KEY, "ar"), "39:24: " + getCheckMessage(MSG_KEY, "int"), "40:16: " + getCheckMessage(MSG_KEY, "int"), - "43:63: " + getCheckMessage(MSG_KEY, "getLongMultArray"), + "43:64: " + getCheckMessage(MSG_KEY, "getLongMultiArray"), "47:26: " + getCheckMessage(MSG_KEY, "}"), "49:22: " + getCheckMessage(MSG_KEY, "int"), "50:24: " + getCheckMessage(MSG_KEY, "]"), @@ -164,6 +165,7 @@ public class NoWhitespaceAfterCheckTest "94:45: " + getCheckMessage(MSG_KEY, ")"), "97:41: " + getCheckMessage(MSG_KEY, "Object"), "100:43: " + getCheckMessage(MSG_KEY, "]"), + "108:31: " + getCheckMessage(MSG_KEY, "Object"), }; verify(checkConfig, getPath("InputNoWhitespaceAfterArrayDeclarations2.java"), expected); } @@ -234,7 +236,7 @@ public class NoWhitespaceAfterCheckTest } /** - * Creates MOCK lexical token and returns AST node for this token + * Creates MOCK lexical token and returns AST node for this token. * @param tokenType type of token * @param tokenText text of token * @param tokenFileName file name of token diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java index 76628ee11..6edb35afb 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java @@ -476,7 +476,7 @@ public class ParenPadCheckTest final Method method = Whitebox.getMethod(ParenPadCheck.class, "isAcceptableToken", DetailAST.class); final DetailAST ast = new DetailAST(); - final String message = "Expected that all accaptable tokens will pass isAccaptableToken " + final String message = "Expected that all acceptable tokens will pass isAcceptableToken " + "method, but some token don't: "; for (int token : check.getAcceptableTokens()) { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java index 769751b75..5af38b101 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; -/** Tests CsvFilter. */ public class CsvFilterTest { @Test public void testDecideSingle() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java index c3678d4e1..2228acadb 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; -/** Tests IntMatchFilter. */ public class IntMatchFilterTest { @Test public void testDecide() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java index 9ae249b67..5fa9fbff1 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java @@ -26,7 +26,6 @@ import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; -/** Tests IntRangeFilter. */ public class IntRangeFilterTest { @Test public void testDecide() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java index 6357f822c..e1ea27ed5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java @@ -20,15 +20,17 @@ package com.puppycrawl.tools.checkstyle.filters; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.api.AuditEvent; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; -/** Tests SeverityMatchFilter. */ public class SeverityMatchFilterTest { private final SeverityMatchFilter filter = new SeverityMatchFilter(); @@ -87,4 +89,10 @@ public class SeverityMatchFilterTest { final AuditEvent ev3 = new AuditEvent(this, "ATest.java", infoMessage); assertFalse("level:" + infoLevel, filter.accept(ev3)); } + + @Test + public void testConfigure() throws CheckstyleException { + filter.configure(new DefaultConfiguration("test")); + assertNotNull("object exists", filter); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java index 922338560..c5e78df7a 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java @@ -33,13 +33,12 @@ import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; -/** Tests SuppressElementFilter. */ public class SuppressElementTest { private SuppressElement filter; @Before public void setUp() { - filter = new SuppressElement("Test", "Test", null, null, null); + filter = new SuppressElement("Test", "Test", null, null, null, null); } @Test @@ -58,16 +57,29 @@ public class SuppressElementTest { } @Test + public void testDecideByMessage() { + final LocalizedMessage message = + new LocalizedMessage(0, 0, "", "", null, null, getClass(), "Test"); + final AuditEvent ev = new AuditEvent(this, "ATest.java", message); + final SuppressElement filter1 = + new SuppressElement(null, null, "Test", null, null, null); + final SuppressElement filter2 = + new SuppressElement(null, null, "Bad", null, null, null); + assertFalse("Message match", filter1.accept(ev)); + assertTrue("Message not match", filter2.accept(ev)); + } + + @Test public void testDecideByLine() { final LocalizedMessage message = new LocalizedMessage(10, 10, "", "", null, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement filter1 = - new SuppressElement("Test", "Test", null, "1-10", null); + new SuppressElement("Test", "Test", null, null, "1-10", null); final SuppressElement filter2 = - new SuppressElement("Test", "Test", null, "1-9, 11", null); + new SuppressElement("Test", "Test", null, null, "1-9, 11", null); final SuppressElement filter3 = - new SuppressElement("Test", "Test", null, null, null); + new SuppressElement("Test", "Test", null, null, null, null); //deny because there are matches on file name, check name, and line assertFalse("In range 1-10", filter1.accept(ev)); assertTrue("Not in 1-9, 11", filter2.accept(ev)); @@ -80,9 +92,9 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement filter1 = - new SuppressElement("Test", "Test", null, null, "1-10"); + new SuppressElement("Test", "Test", null, null, null, "1-10"); final SuppressElement filter2 = - new SuppressElement("Test", "Test", null, null, "1-9, 11"); + new SuppressElement("Test", "Test", null, null, null, "1-9, 11"); //deny because there are matches on file name, check name, and column assertFalse("In range 1-10", filter1.accept(ev)); @@ -117,7 +129,7 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, "MyModule", getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement myFilter = - new SuppressElement("Test", "Test", "MyModule", null, null); + new SuppressElement("Test", "Test", null, "MyModule", null, null); assertFalse("Filter should not accept invalid event", myFilter.accept(ev)); } @@ -128,7 +140,7 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, "TheirModule", getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement myFilter = - new SuppressElement("Test", "Test", "MyModule", null, null); + new SuppressElement("Test", "Test", null, "MyModule", null, null); assertTrue("Filter should accept valid event", myFilter.accept(ev)); } @@ -147,7 +159,7 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "TestSUFFIX", message); final SuppressElement myFilter = - new SuppressElement("Test", null, null, null, null); + new SuppressElement("Test", null, null, null, null, null); assertFalse("Filter should not accept invalid event", myFilter.accept(ev)); } @@ -157,7 +169,7 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement myFilter = - new SuppressElement("Test", "NON_EXISTING_CHECK", "MyModule", null, null); + new SuppressElement("Test", "NON_EXISTENT_CHECK", null, "MyModule", null, null); assertTrue("Filter should accept valid event", myFilter.accept(ev)); } @@ -167,7 +179,7 @@ public class SuppressElementTest { new LocalizedMessage(10, 10, "", "", null, null, getClass(), null); final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement myFilter = - new SuppressElement("Test", getClass().getCanonicalName(), null, null, null); + new SuppressElement("Test", getClass().getCanonicalName(), null, null, null, null); assertFalse("Filter should not accept invalid event", myFilter.accept(ev)); } @@ -179,7 +191,7 @@ public class SuppressElementTest { final AuditEvent ev = new AuditEvent(this, "ATest.java", message); final SuppressElement myFilter = new SuppressElement("Test", TreeWalkerTest.class.getCanonicalName(), - null, null, null); + null, null, null, null); assertTrue("Filter should not accept invalid event", myFilter.accept(ev)); } @@ -189,27 +201,27 @@ public class SuppressElementTest { // filterBased is used instead of filter field only to satisfy IntelliJ Idea Inspection // Inspection "Arguments to assertEquals() in wrong order " final SuppressElement filterBased = - new SuppressElement("Test", "Test", null, null, null); + new SuppressElement("Test", "Test", null, null, null, null); final SuppressElement filter2 = - new SuppressElement("Test", "Test", null, null, null); + new SuppressElement("Test", "Test", null, null, null, null); assertEquals("filter, filter2", filterBased, filter2); final SuppressElement filter3 = - new SuppressElement("Test", "Test3", null, null, null); + new SuppressElement("Test", "Test3", null, null, null, null); assertNotEquals("filter, filter3", filterBased, filter3); final SuppressElement filterBased1 = - new SuppressElement("Test", "Test", null, null, "1-10"); + new SuppressElement("Test", "Test", null, null, null, "1-10"); assertNotEquals("filter, filter2", filterBased1, filter2); final SuppressElement filter22 = - new SuppressElement("Test", "Test", null, null, "1-10"); + new SuppressElement("Test", "Test", null, null, null, "1-10"); assertEquals("filter, filter2", filterBased1, filter22); assertNotEquals("filter, filter2", filterBased1, filter2); final SuppressElement filterBased2 = - new SuppressElement("Test", "Test", null, "3,4", null); + new SuppressElement("Test", "Test", null, null, "3,4", null); assertNotEquals("filter, filter2", filterBased2, filter2); final SuppressElement filter23 = - new SuppressElement("Test", "Test", null, "3,4", null); + new SuppressElement("Test", "Test", null, null, "3,4", null); assertEquals("filter, filter2", filterBased2, filter23); assertNotEquals("filter, filter2", filterBased2, filter2); assertEquals("filter, filter2", filterBased2, filter23); @@ -219,7 +231,8 @@ public class SuppressElementTest { public void testEqualsAndHashCode() { EqualsVerifier.forClass(SuppressElement.class) .usingGetClass() - .withIgnoredFields("fileRegexp", "checkRegexp", "columnFilter", "lineFilter") + .withIgnoredFields("fileRegexp", "checkRegexp", "messageRegexp", "columnFilter", + "lineFilter") .suppress(Warning.NONFINAL_FIELDS) .verify(); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java new file mode 100644 index 000000000..9f717333f --- /dev/null +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java @@ -0,0 +1,487 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2017 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//////////////////////////////////////////////////////////////////////////////// + +package com.puppycrawl.tools.checkstyle.filters; + +import static com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck.MSG_CONTAINS_TAB; +import static com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck.MSG_FILE_CONTAINS_TAB; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +import org.junit.Assert; +import org.junit.Test; + +import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.api.AuditEvent; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; +import com.puppycrawl.tools.checkstyle.api.SeverityLevel; +import com.puppycrawl.tools.checkstyle.api.TokenTypes; +import com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck; +import com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck; +import com.puppycrawl.tools.checkstyle.utils.CommonUtils; +import nl.jqno.equalsverifier.EqualsVerifier; + +public class SuppressWithPlainTextCommentFilterTest extends AbstractModuleTestSupport { + + private static final String MSG_REGEXP_EXCEEDED = "regexp.exceeded"; + + @Override + protected String getPackageLocation() { + return "com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter"; + } + + @Test + public void testFilterWithDefaultConfig() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + final String[] violationMessages = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testChangeOffAndOnFormat() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("onCommentFormat", "cs-on"); + filterCfg.addAttribute("offCommentFormat", "cs-off"); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "11:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "13:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + final String[] violationMessage = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "11:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java", + removeSuppressed(violationMessage, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testSuppressionCommentsInXmlFile() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "CS-OFF"); + filterCfg.addAttribute("onCommentFormat", "CS-ON"); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = { + "7:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + final String[] violationMessages = { + "7:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilter.xml", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testSuppressionCommentsInPropertiesFile() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "# CHECKSTYLE:OFF"); + filterCfg.addAttribute("onCommentFormat", "# CHECKSTYLE:ON"); + + final DefaultConfiguration checkCfg = createModuleConfig(RegexpSinglelineCheck.class); + checkCfg.addAttribute("format", "^key[0-9]=$"); + + final String[] suppressed = { + "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + "^key[0-9]=$"), + }; + + final String[] violationMessages = { + "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + "^key[0-9]=$"), + "4: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + "^key[0-9]=$"), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilter.properties", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testSuppressionCommentsInSqlFile() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "-- CHECKSTYLE OFF"); + filterCfg.addAttribute("onCommentFormat", "-- CHECKSTYLE ON"); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = { + "2:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + final String[] violationMessages = { + "2:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "5:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilter.sql", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testSuppressionCommentsInJavaScriptFile() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "// CS-OFF"); + filterCfg.addAttribute("onCommentFormat", "// CS-ON"); + + final DefaultConfiguration checkCfg = createModuleConfig(RegexpSinglelineCheck.class); + checkCfg.addAttribute("format", ".*===.*"); + + final String[] suppressed = { + "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"), + }; + + final String[] violationMessages = { + "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"), + "5: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilter.js", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + } + + @Test + public void testInvalidCheckFormat() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("checkFormat", "e[l"); + filterCfg.addAttribute("onCommentFormat", "// cs-on"); + filterCfg.addAttribute("offCommentFormat", "// cs-off"); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = CommonUtils.EMPTY_STRING_ARRAY; + + final String[] violationMessages = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + try { + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + fail("CheckstyleException is expected"); + } + catch (CheckstyleException ex) { + final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause(); + assertEquals("Invalid exception message", + "unable to parse expanded comment e[l", cause.getMessage()); + } + } + + @Test + public void testInvalidMessageFormat() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("messageFormat", "e[l"); + filterCfg.addAttribute("onCommentFormat", "// cs-on"); + filterCfg.addAttribute("offCommentFormat", "// cs-off"); + + final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class); + checkCfg.addAttribute("eachLine", "true"); + + final String[] suppressed = CommonUtils.EMPTY_STRING_ARRAY; + + final String[] violationMessages = { + "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB), + "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + try { + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java", + removeSuppressed(violationMessages, suppressed), + filterCfg, checkCfg + ); + fail("CheckstyleException is expected"); + } + catch (CheckstyleException ex) { + final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause(); + assertEquals("Invalid exception message", + "unable to parse expanded comment e[l", cause.getMessage()); + } + } + + @Test + public void testAcceptNullLocalizedMessage() { + final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter(); + final AuditEvent auditEvent = new AuditEvent(this); + assertTrue("Filter should accept audit event", filter.accept(auditEvent)); + Assert.assertNull("File name should not be null", auditEvent.getFileName()); + } + + @Test + public void testEqualsAndHashCodeOfTagClass() { + EqualsVerifier.forClass(SuppressWithPlainTextCommentFilter.Suppression.class) + .usingGetClass().verify(); + } + + @Test + public void testSuppressByModuleId() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "CSOFF (\\w+) \\(\\w+\\)"); + filterCfg.addAttribute("onCommentFormat", "CSON (\\w+)"); + filterCfg.addAttribute("checkFormat", "$1"); + + final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class); + regexpCheckCfg.addAttribute("id", "ignore"); + regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*"); + + final DefaultConfiguration fileTabCheckCfg = + createModuleConfig(FileTabCharacterCheck.class); + fileTabCheckCfg.addAttribute("eachLine", "true"); + fileTabCheckCfg.addAttribute("id", "foo"); + + final String[] suppressedViolationMessages = { + "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + }; + + final String[] expectedViolationMessages = { + "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "9:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "14: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterSuppressById.java", + removeSuppressed(expectedViolationMessages, suppressedViolationMessages), + filterCfg, regexpCheckCfg, fileTabCheckCfg + ); + } + + @Test + public void testSuppressByModuleIdWithNullModuleId() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + filterCfg.addAttribute("offCommentFormat", "CSOFF (\\w+) \\(\\w+\\)"); + filterCfg.addAttribute("onCommentFormat", "CSON (\\w+)"); + filterCfg.addAttribute("checkFormat", "$1"); + + final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class); + regexpCheckCfg.addAttribute("id", "ignore"); + regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*"); + + final DefaultConfiguration fileTabCheckCfg = + createModuleConfig(FileTabCharacterCheck.class); + fileTabCheckCfg.addAttribute("eachLine", "true"); + fileTabCheckCfg.addAttribute("id", null); + + final String[] suppressedViolationMessages = { + "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + }; + + final String[] expectedViolationMessages = { + "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "9:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "14: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterSuppressById.java", + removeSuppressed(expectedViolationMessages, suppressedViolationMessages), + filterCfg, regexpCheckCfg, fileTabCheckCfg + ); + } + + @Test + public void testAcceptThrowsIllegalStateExceptionAsFileNotFound() { + final LocalizedMessage message = new LocalizedMessage(1, 1, 1, TokenTypes.CLASS_DEF, + "messages.properties", "key", null, SeverityLevel.ERROR, null, getClass(), null); + final String fileName = "nonexisting_file"; + final AuditEvent auditEvent = new AuditEvent(this, fileName, message); + + final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter(); + + try { + filter.accept(auditEvent); + fail(IllegalStateException.class.getSimpleName() + " is expected"); + } + catch (IllegalStateException ex) { + assertEquals("Invalid exception message", + "Cannot read source file: " + fileName, ex.getMessage()); + + final Throwable cause = ex.getCause(); + assertTrue("Exception cause has invalid type", + cause instanceof FileNotFoundException); + assertEquals("Invalid exception message", + fileName + " (No such file or directory)", cause.getMessage()); + } + } + + @Test + public void testFilterWithCustomMessageFormat() throws Exception { + final DefaultConfiguration filterCfg = + createModuleConfig(SuppressWithPlainTextCommentFilter.class); + final String messageFormat = + ".*" + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB) + ".*"; + // -@cs[CheckstyleTestMakeup] need to test dynamic property + filterCfg.addAttribute("messageFormat", messageFormat); + + final DefaultConfiguration fileTabCheckCfg = + createModuleConfig(FileTabCharacterCheck.class); + fileTabCheckCfg.addAttribute("eachLine", "true"); + + final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class); + regexpCheckCfg.addAttribute("id", "ignore"); + regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*"); + + final String[] suppressed = { + "8:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + }; + + final String[] violationMessages = { + "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "8:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB), + "8: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "10: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + "13: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, + ".*[a-zA-Z][0-9].*"), + }; + + verifySuppressed( + "InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java", + removeSuppressed(violationMessages, suppressed), + filterCfg, fileTabCheckCfg, regexpCheckCfg + ); + } + + @Test + public void testFilterWithDirectory() throws IOException { + final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter(); + final AuditEvent event = new AuditEvent(this, getPath(""), new LocalizedMessage(1, 1, + "bundle", "key", null, SeverityLevel.ERROR, "moduleId", getClass(), + "customMessage")); + + assertTrue("filter should accept directory", filter.accept(event)); + } + + private void verifySuppressed(String fileNameWithExtension, String[] violationMessages, + Configuration... childConfigs) throws Exception { + final DefaultConfiguration checkerConfig = createRootConfig(null); + + Arrays.stream(childConfigs).forEach(checkerConfig::addChild); + + final String fileExtension = CommonUtils.getFileExtension(fileNameWithExtension); + checkerConfig.addAttribute("fileExtensions", fileExtension); + + verify(checkerConfig, getPath(fileNameWithExtension), violationMessages); + } + + private static String[] removeSuppressed(String[] from, String... remove) { + final Collection<String> coll = Arrays.stream(from).collect(Collectors.toList()); + coll.removeAll(Arrays.asList(remove)); + return coll.toArray(new String[coll.size()]); + } +} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java index 229a9b9af..36835cab2 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java @@ -401,7 +401,7 @@ public class SuppressionCommentFilterTest final TreeWalkerAuditEvent dummyEvent = new TreeWalkerAuditEvent(contents, "filename", new LocalizedMessage(1, null, null, null, null, Object.class, null), null); final boolean result = suppressionCommentFilter.accept(dummyEvent); - assertFalse("Fileter should not accept event", result); + assertFalse("Filter should not accept event", result); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java index f0e9e8182..340485868 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java @@ -85,8 +85,8 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingSuppressionFileWithFalseOptional() { - final String fileName = "non_existing_suppression_file.xml"; + public void testNonExistentSuppressionFileWithFalseOptional() { + final String fileName = "non_existent_suppression_file.xml"; try { final boolean optional = false; createSuppressionFilter(fileName, optional); @@ -108,7 +108,7 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport { } catch (CheckstyleException ex) { assertEquals("Invalid error message", - "Unable to parse " + fileName + " - invalid files or checks format", + "Unable to parse " + fileName + " - invalid files or checks or message format", ex.getMessage()); } } @@ -126,8 +126,8 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingSuppressionFileWithTrueOptional() throws Exception { - final String fileName = "non_existing_suppression_file.xml"; + public void testNonExistentSuppressionFileWithTrueOptional() throws Exception { + final String fileName = "non_existent_suppression_file.xml"; final boolean optional = true; final SuppressionFilter filter = createSuppressionFilter(fileName, optional); @@ -138,9 +138,9 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingSuppressionUrlWithTrueOptional() throws Exception { + public void testNonExistentSuppressionUrlWithTrueOptional() throws Exception { final String fileName = - "http://checkstyle.sourceforge.net/non_existing_suppression.xml"; + "http://checkstyle.sourceforge.net/non_existent_suppression.xml"; final boolean optional = true; final SuppressionFilter filter = createSuppressionFilter(fileName, optional); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java index 97b9c1eff..a7fe7ce4c 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java @@ -86,8 +86,8 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingSuppressionFileWithFalseOptional() throws Exception { - final String fileName = getPath("non_existing_suppression_file.xml"); + public void testNonExistentSuppressionFileWithFalseOptional() throws Exception { + final String fileName = getPath("non_existent_suppression_file.xml"); try { final boolean optional = false; createSuppressionXpathFilter(fileName, optional); @@ -108,9 +108,8 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport { fail("Exception is expected"); } catch (CheckstyleException ex) { - assertEquals("Invalid error message", - "Unable to parse " + fileName + " - invalid files or checks format for " - + "suppress-xpath", + assertEquals("Invalid error message", "Unable to parse " + fileName + + " - invalid files or checks or message format for suppress-xpath", ex.getMessage()); } } @@ -129,9 +128,9 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport { } @Test - public void testNonExistingSuppressionFileWithTrueOptional() throws Exception { + public void testNonExistentSuppressionFileWithTrueOptional() throws Exception { final String fileName = "src/test/resources/com/puppycrawl/tools/checkstyle/filters/" - + "non_existing_suppression_file.xml"; + + "non_existent_suppression_file.xml"; final boolean optional = true; final SuppressionXpathFilter filter = createSuppressionXpathFilter(fileName, optional); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java index 0a7be080b..294599ecd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; +import java.util.HashSet; import java.util.Set; import org.junit.Rule; @@ -104,7 +105,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { } @Test - public void testLoadFromNonExistingUrl() { + public void testLoadFromNonExistentUrl() { try { SuppressionsLoader.loadSuppressions("http://^%$^* %&% %^&"); fail("exception expected"); @@ -122,17 +123,20 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { final FilterSet fc2 = new FilterSet(); final SuppressElement se0 = - new SuppressElement("file0", "check0", null, null, null); + new SuppressElement("file0", "check0", null, null, null, null); fc2.addFilter(se0); final SuppressElement se1 = - new SuppressElement("file1", "check1", null, "1,2-3", null); + new SuppressElement("file1", "check1", null, null, "1,2-3", null); fc2.addFilter(se1); final SuppressElement se2 = - new SuppressElement("file2", "check2", null, null, "1,2-3"); + new SuppressElement("file2", "check2", null, null, null, "1,2-3"); fc2.addFilter(se2); final SuppressElement se3 = - new SuppressElement("file3", "check3", null, "1,2-3", "1,2-3"); + new SuppressElement("file3", "check3", null, null, "1,2-3", "1,2-3"); fc2.addFilter(se3); + final SuppressElement se4 = + new SuppressElement(null, null, "message0", null, null, null); + fc2.addFilter(se4); assertEquals("Multiple suppressions were loaded incorrectly", fc2, fc); } @@ -268,7 +272,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { } catch (CheckstyleException ex) { assertEquals("Invalid error message", - "Unable to parse " + fn + " - missing checks and id attribute", + "Unable to parse " + fn + " - missing checks or id or message attribute", ex.getMessage()); } } @@ -290,7 +294,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { } catch (CheckstyleException ex) { assertEquals("Invalid error message", - "Unable to parse " + fn + " - invalid files or checks format", + "Unable to parse " + fn + " - invalid files or checks or message format", ex.getMessage()); } } @@ -318,7 +322,15 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { final String fn = getPath("InputSuppressionsLoaderXpathCorrect.xml"); final Set<TreeWalkerFilter> filterSet = SuppressionsLoader.loadXpathSuppressions(fn); - assertEquals("Invalid number of filters", 1, filterSet.size()); + final Set<TreeWalkerFilter> expectedFilterSet = new HashSet<>(); + final XpathFilter xf0 = + new XpathFilter("file1", "test", null, "id1", "/CLASS_DEF"); + expectedFilterSet.add(xf0); + final XpathFilter xf1 = + new XpathFilter(null, null, "message1", null, "/CLASS_DEF"); + expectedFilterSet.add(xf1); + assertEquals("Multiple xpath suppressions were loaded incorrectly", expectedFilterSet, + filterSet); } @Test @@ -330,7 +342,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { } catch (CheckstyleException ex) { assertEquals("Invalid error message", - "Unable to parse " + fn + " - invalid files or checks format for " + "Unable to parse " + fn + " - invalid files or checks or message format for " + "suppress-xpath", ex.getMessage()); } @@ -346,7 +358,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport { } catch (CheckstyleException ex) { assertEquals("Invalid error message", - "Unable to parse " + fn + " - missing checks and id attribute for " + "Unable to parse " + fn + " - missing checks or id or message attribute for " + "suppress-xpath", ex.getMessage()); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java index f74af313e..4580cd3e4 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java @@ -61,7 +61,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testMatching() throws Exception { final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 0, TokenTypes.CLASS_DEF); assertFalse("Event should be rejected", filter.accept(ev)); @@ -71,7 +71,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingTokenType() throws Exception { final String xpath = "//METHOD_DEF[@text='countTokens']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 0, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); @@ -81,7 +81,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingLineNumber() throws Exception { final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(100, 0, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); @@ -91,7 +91,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingColumnNumber() throws Exception { final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 100, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); @@ -103,7 +103,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { + "../..[@text='countTokens']] " + "| //VARIABLE_DEF[@text='someVariable' and ../..[@text='sum']]"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent eventOne = getEvent(5, 8, TokenTypes.VARIABLE_DEF); final TreeWalkerAuditEvent eventTwo = getEvent(10, 4, @@ -120,7 +120,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { final String xpath = "1@#"; try { final Object test = new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, - xpath); + null, xpath); fail("Exception was expected but got " + test); } catch (IllegalStateException ex) { @@ -134,15 +134,15 @@ public class XpathFilterTest extends AbstractModuleTestSupport { final TreeWalkerAuditEvent event = getEvent(15, 8, TokenTypes.VARIABLE_DEF); final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null); - assertTrue("Event should be accepted", filter.accept(event)); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, null); + assertFalse("Event should be accepted", filter.accept(event)); } @Test public void testNullFileName() { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(null, null, null, null); assertTrue("Event should be accepted", filter.accept(ev)); @@ -152,7 +152,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingFileRegexp() throws Exception { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = - new XpathFilter("NonMatchingRegexp", "Test", null, xpath); + new XpathFilter("NonMatchingRegexp", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 0, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); @@ -162,7 +162,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNullLocalizedMessage() { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(null, file.getName(), null, null); assertTrue("Event should be accepted", filter.accept(ev)); @@ -172,7 +172,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingModuleId() throws Exception { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", "id19", xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, "id19", xpath); final LocalizedMessage message = new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id20", getClass(), null); @@ -185,7 +185,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testMatchingModuleId() throws Exception { final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", "id19", xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, "id19", xpath); final LocalizedMessage message = new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19", getClass(), null); @@ -198,7 +198,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingChecks() throws Exception { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = new XpathFilter("InputXpathFilterSuppressByXpath", - "NonMatchingRegexp", "id19", xpath); + "NonMatchingRegexp", null, "id19", xpath); final LocalizedMessage message = new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19", getClass(), null); @@ -211,7 +211,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNonMatchingFileNameModuleIdAndCheck() throws Exception { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", null, null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", null, null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 0, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); @@ -221,17 +221,29 @@ public class XpathFilterTest extends AbstractModuleTestSupport { public void testNullModuleIdAndNonMatchingChecks() throws Exception { final String xpath = "NON_MATCHING_QUERY"; final XpathFilter filter = new XpathFilter("InputXpathFilterSuppressByXpath", - "NonMatchingRegexp", null, xpath); + "NonMatchingRegexp", null, null, xpath); final TreeWalkerAuditEvent ev = getEvent(3, 0, TokenTypes.CLASS_DEF); assertTrue("Event should be accepted", filter.accept(ev)); } @Test + public void testDecideByMessage() throws Exception { + final LocalizedMessage message = new LocalizedMessage(0, 0, TokenTypes.CLASS_DEF, "", "", + null, null, null, getClass(), "Test"); + final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(fileContents, file.getName(), + message, TestUtil.parseFile(file)); + final XpathFilter filter1 = new XpathFilter(null, null, "Test", null, null); + final XpathFilter filter2 = new XpathFilter(null, null, "Bad", null, null); + assertFalse("Message match", filter1.accept(ev)); + assertTrue("Message not match", filter2.accept(ev)); + } + + @Test public void testThrowException() { final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']"; final XpathFilter filter = - new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath); + new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath); final LocalizedMessage message = new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19", getClass(), null); @@ -254,7 +266,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport { xpathEvaluator.createExpression("//METHOD_DEF"), xpathEvaluator.createExpression("//VARIABLE_DEF")) .usingGetClass() - .withIgnoredFields("fileRegexp", "checkRegexp", "xpathExpression") + .withIgnoredFields("fileRegexp", "checkRegexp", "messageRegexp", "xpathExpression") .verify(); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java index 54b3f866a..ea49bf979 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java @@ -22,7 +22,10 @@ package com.puppycrawl.tools.checkstyle.grammars; import org.junit.Assert; import org.junit.Test; -/** @noinspection ClassIndependentOfModule */ +/** + * GeneratedJavaTokenTypesTest. + * @noinspection ClassIndependentOfModule + */ public class GeneratedJavaTokenTypesTest { /** * <p> @@ -30,6 +33,7 @@ public class GeneratedJavaTokenTypesTest { * old tokens must remain and keep their current numbering. Old token * numberings are not allowed to change. * </p> + * * <p> * The reason behind this is Java inlines static final field values directly * into the compiled Java code. This loses all connections with the original @@ -37,7 +41,9 @@ public class GeneratedJavaTokenTypesTest { * up in user-created checks and causes conflicts. * </p> * + * <p> * Issue: https://github.com/checkstyle/checkstyle/issues/505 + * </p> */ @Test public void testTokenNumbering() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java index c90a188ed..fe4d2ed6e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java @@ -23,7 +23,10 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -/** @noinspection ClassIndependentOfModule */ +/** + * GeneratedJavadocTokenTypesTest. + * @noinspection ClassIndependentOfModule + */ public class GeneratedJavadocTokenTypesTest { private static final String MSG = "Ensure that token numbers generated for the elements" @@ -33,7 +36,7 @@ public class GeneratedJavadocTokenTypesTest { * This method checks that the numbers generated for tokens in <tt>JavadocLexer.g4</tt> don't * change with the lexer grammar itself. * <br>ANTLR maps all the lexer elements to compile time constants used internally by ANTLR. - * Compatability damange is incurred <i>(with respect to the previous checkstyle versions) + * Compatibility damage is incurred <i>(with respect to the previous checkstyle versions) * </i> if these compile time constants keep changing with the grammar. * * @see "https://github.com/checkstyle/checkstyle/issues/5139" @@ -143,7 +146,7 @@ public class GeneratedJavadocTokenTypesTest { * This method checks that the numbers generated for rules in <tt>JavadocParser.g4</tt> don't * change with the Parser grammar itself. * <br>ANTLR maps all the parser rules to compile time constants used internally by ANTLR. - * Compatability damange is incurred <i>(with respect to the previous checkstyle versions) + * Compatibility damage is incurred <i>(with respect to the previous checkstyle versions) * </i> if these compile time constants keep changing with the grammar. * * @see "https://github.com/checkstyle/checkstyle/issues/5139" diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java index ebfb522d6..ff70d9290 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java @@ -26,7 +26,10 @@ import org.junit.Test; import com.puppycrawl.tools.checkstyle.AbstractTreeTestSupport; -/** @noinspection ClassOnlyUsedInOnePackage */ +/** + * JavadocParseTreeTest. + * @noinspection ClassOnlyUsedInOnePackage + */ public class JavadocParseTreeTest extends AbstractTreeTestSupport { @Override diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java index 8adea5082..dc9e16aa4 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java @@ -56,7 +56,7 @@ public class CodeSelectorPresentationTest extends AbstractPathTestSupport { } /** Converts lineToPosition from multicharacter to one character line separator - * needs to support crossplatform line separators + * needs to support crossplatform line separators. * @param systemLinesToPosition lines to position mapping for current system * @return lines to position mapping with one character line separator */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java index afd5a7f85..03e720960 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java @@ -191,18 +191,19 @@ public class ParseTreeTablePresentationTest extends AbstractPathTestSupport { final ParseTreeTablePresentation parseTree = new ParseTreeTablePresentation(null); int index = 0; while (ithChild != null) { - Assert.assertEquals("Invalud child index", + Assert.assertEquals("Invalid child index", index, parseTree.getIndexOfChild(tree, ithChild)); ithChild = ithChild.getNextSibling(); index++; } - Assert.assertEquals("Invalud child index", + Assert.assertEquals("Invalid child index", -1, parseTree.getIndexOfChild(tree, new DetailAST())); } /** - * The path to class name in InputJavadocAttributesAndMethods.java + * The path to class name in InputJavadocAttributesAndMethods.java. + * <pre> * CLASS_DEF * - MODIFIERS * - Comment node @@ -210,6 +211,7 @@ public class ParseTreeTablePresentationTest extends AbstractPathTestSupport { * - IDENT -> this is the node that holds the class name * Line number 4 - first three lines are taken by javadoc * Column 6 - first five columns taken by 'class ' + * </pre> */ @Test public void testGetValueAt() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java index 38c24c739..f82155485 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java @@ -330,8 +330,6 @@ public class AllChecksTest extends AbstractModuleTestSupport { public void testAllModulesAreReferencedInConfigFile() throws Exception { final Set<String> modulesReferencedInConfig = CheckUtil.getConfigCheckStyleModules(); final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules()); - //Issue: https://github.com/checkstyle/checkstyle/issues/4421 - moduleNames.remove("SuppressionXpathFilter"); moduleNames.stream().filter(check -> !modulesReferencedInConfig.contains(check)) .forEach(check -> { @@ -428,8 +426,6 @@ public class AllChecksTest extends AbstractModuleTestSupport { // these are documented on non-'config_' pages checkstyleModulesNames.remove("TreeWalker"); checkstyleModulesNames.remove("Checker"); - //Issue: https://github.com/checkstyle/checkstyle/issues/4421 - checkstyleModulesNames.remove("SuppressionXpathFilter"); checkstyleModulesNames.stream() .filter(moduleName -> !modulesNamesWhichHaveXdocs.contains(moduleName)) @@ -445,8 +441,6 @@ public class AllChecksTest extends AbstractModuleTestSupport { public void testAllCheckstyleModulesInCheckstyleConfig() throws Exception { final Set<String> configChecks = CheckUtil.getConfigCheckStyleModules(); final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules()); - //Issue: https://github.com/checkstyle/checkstyle/issues/4421 - moduleNames.remove("SuppressionXpathFilter"); for (String moduleName : moduleNames) { Assert.assertTrue("checkstyle_checks.xml is missing module: " + moduleName, @@ -548,6 +542,7 @@ public class AllChecksTest extends AbstractModuleTestSupport { * Checks that an array is a subset of other array. * @param array to check whether it is a subset. * @param arrayToCheckIn array to check in. + * @return {@code true} if all elements in {@code array} are in {@code arrayToCheckIn}. */ private static boolean isSubset(int[] array, int... arrayToCheckIn) { Arrays.sort(arrayToCheckIn); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java index b7269b536..d9c4c5e3f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java @@ -32,7 +32,10 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; -/** @noinspection ClassIndependentOfModule */ +/** + * AllTestsTest. + * @noinspection ClassIndependentOfModule + */ public class AllTestsTest { @Test public void testAllInputsHaveTest() throws Exception { @@ -143,7 +146,6 @@ public class AllTestsTest { // until https://github.com/checkstyle/checkstyle/issues/5105 if (!path.contains(File.separatorChar + "grammars" + File.separatorChar) - // until https://github.com/checkstyle/checkstyle/issues/5104 && !path.contains(File.separatorChar + "foo" + File.separatorChar) && !path.contains(File.separatorChar + "bar" + File.separatorChar)) { String fileName = file.getName(); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java index ede921efe..f6323466e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java @@ -49,24 +49,24 @@ import org.junit.Test; /** * Validate commit message has proper structure. * - * Commits to check are resolved from different places according + * <p>Commits to check are resolved from different places according * to type of commit in current HEAD. If current HEAD commit is * non-merge commit , previous commits are resolved due to current * HEAD commit. Otherwise if it is a merge commit, it will invoke - * resolving previous commits due to commits which was merged. + * resolving previous commits due to commits which was merged.</p> * - * After calculating commits to start with ts resolves previous + * <p>After calculating commits to start with ts resolves previous * commits according to COMMITS_RESOLUTION_MODE variable. * At default(BY_LAST_COMMIT_AUTHOR) it checks first commit author * and return all consecutive commits with same author. Second * mode(BY_COUNTER) makes returning first PREVIOUS_COMMITS_TO_CHECK_COUNT - * commits after starter commit. + * commits after starter commit.</p> * - * Resolved commits are filtered according to author. If commit author + * <p>Resolved commits are filtered according to author. If commit author * belong to list USERS_EXCLUDED_FROM_VALIDATION then this commit will - * not be validated. + * not be validated.</p> * - * Filtered commit list is checked if their messages has proper structure. + * <p>Filtered commit list is checked if their messages has proper structure.</p> * * @author <a href="mailto:piotr.listkiewicz@gmail.com">liscju</a> */ diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java index 129d67c08..5f88ab111 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java @@ -84,6 +84,7 @@ public class XdocsPagesTest { "name=\"Header\"", "name=\"Translation\"", "name=\"SeverityMatchFilter\"", + "name=\"SuppressWithPlainTextCommentFilter\"", "name=\"SuppressionFilter\"", "name=\"SuppressWarningsFilter\"", "name=\"BeforeExecutionExclusionFileFilter\"", @@ -215,6 +216,7 @@ public class XdocsPagesTest { // can't process non-existent examples, or out of context snippets if (!code.contains("com.mycompany") && !code.contains("checkstyle-packages") && !code.contains("MethodLimit") && !code.contains("<suppress ") + && !code.contains("<suppress-xpath ") && !code.contains("<import-control ") && !unserializedSource.startsWith("<property ") && !unserializedSource.startsWith("<taskdef ")) { @@ -292,7 +294,7 @@ public class XdocsPagesTest { } /** - * Test contains asserts in callstack, but idea does not see them + * Test contains asserts in callstack, but idea does not see them. * @noinspection JUnitTestMethodWithNoAssertions */ @Test @@ -450,6 +452,9 @@ public class XdocsPagesTest { if (hasParentModule(sectionName)) { if (AbstractJavadocCheck.class.isAssignableFrom(clss)) { properties.removeAll(JAVADOC_CHECK_PROPERTIES); + + // override + properties.add("violateExecutionOnNonTightHtml"); } else if (AbstractCheck.class.isAssignableFrom(clss)) { properties.removeAll(CHECK_PROPERTIES); @@ -643,7 +648,14 @@ public class XdocsPagesTest { .replaceAll("\\s+", " ").trim()); } - /** @noinspection IfStatementWithTooManyBranches */ + /** + * Get's the name of the bean property's type for the class. + * @param clss The bean property's defined type. + * @param instance The class instance to work with. + * @param propertyName The property name to work with. + * @return String form of property's type. + * @noinspection IfStatementWithTooManyBranches + */ private static String getModulePropertyExpectedTypeName(Class<?> clss, Object instance, String propertyName) { final String instanceName = instance.getClass().getSimpleName(); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java index f5ea98b15..c6b6cb0f1 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java @@ -26,6 +26,7 @@ import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.FileText; /** + * TestFileSetCheck. * @noinspection ClassOnlyUsedInOnePackage */ public class TestFileSetCheck extends AbstractFileSetCheck { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java index 2bf6b9f8a..005a58f1d 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java @@ -22,6 +22,7 @@ package com.puppycrawl.tools.checkstyle.internal.testmodules; import com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter; /** + * TestLoggingReporter. * @noinspection ClassOnlyUsedInOnePackage */ public final class TestLoggingReporter extends AbstractViolationReporter { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java index be0898136..8a25a6cce 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java @@ -139,7 +139,7 @@ public final class CheckUtil { .getContextClassLoader(); final String packageName = "com.puppycrawl.tools.checkstyle"; return getCheckstyleModulesRecursive(packageName, loader).stream() - .filter(ModuleReflectionUtils::isCheckstyleCheck) + .filter(ModuleReflectionUtils::isCheckstyleTreeWalkerCheck) .collect(Collectors.toSet()); } @@ -219,6 +219,7 @@ public final class CheckUtil { * Gets the check message 'as is' from appropriate 'messages.properties' * file. * + * @param module The package the message is located in. * @param locale the locale to get the message for. * @param messageKey the key of message in 'messages*.properties' file. * @param arguments the arguments of message in 'messages*.properties' file. diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java index 6eb65dd1f..cf62e8b6f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java @@ -22,7 +22,10 @@ package com.puppycrawl.tools.checkstyle.internal.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; -/** @noinspection ClassOnlyUsedInOnePackage */ +/** + * CloseAndFlushTestByteArrayOutputStream. + * @noinspection ClassOnlyUsedInOnePackage + */ public final class CloseAndFlushTestByteArrayOutputStream extends ByteArrayOutputStream { private int closeCount; diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java index 948a55197..a88fb960a 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java @@ -38,6 +38,7 @@ public final class ConfigurationUtil { props.setProperty("checkstyle.basedir", "basedir"); props.setProperty("checkstyle.cache.file", "file"); props.setProperty("checkstyle.suppressions.file", "file"); + props.setProperty("checkstyle.suppressions-xpath.file", "file"); props.setProperty("checkstyle.header.file", "file"); props.setProperty("checkstyle.regexp.header.file", "file"); props.setProperty("checkstyle.importcontrol.file", "file"); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java index 1c5d8cc70..df85e9aad 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java @@ -25,6 +25,7 @@ import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -72,6 +73,52 @@ public final class TestUtil { } /** + * Retrieves the specified field by it's name in the class or it's direct super. + * + * @param clss The class to retrieve the field for. + * @param fieldName The name of the field to retrieve. + * @return The class' field. + * @throws NoSuchFieldException if the requested field cannot be found in the class. + */ + public static Field getClassDeclaredField(Class<?> clss, String fieldName) + throws NoSuchFieldException { + final Optional<Field> classField = Arrays.stream(clss.getDeclaredFields()) + .filter(field -> fieldName.equals(field.getName())).findFirst(); + final Field resultField; + if (classField.isPresent()) { + resultField = classField.get(); + } + else { + resultField = clss.getSuperclass().getDeclaredField(fieldName); + } + resultField.setAccessible(true); + return resultField; + } + + /** + * Retrieves the specified method by it's name in the class or it's direct super. + * + * @param clss The class to retrieve the field for. + * @param methodName The name of the method to retrieve. + * @return The class' field. + * @throws NoSuchMethodException if the requested method cannot be found in the class. + */ + public static Method getClassDeclaredMethod(Class<?> clss, String methodName) + throws NoSuchMethodException { + final Optional<Method> classMethod = Arrays.stream(clss.getDeclaredMethods()) + .filter(method -> methodName.equals(method.getName())).findFirst(); + final Method resultMethod; + if (classMethod.isPresent()) { + resultMethod = classMethod.get(); + } + else { + resultMethod = clss.getSuperclass().getDeclaredMethod(methodName); + } + resultMethod.setAccessible(true); + return resultMethod; + } + + /** * Checks if stateful field is cleared during {@link AbstractCheck#beginTree} in check. * * @param check check object which field is to be verified @@ -91,16 +138,7 @@ public final class TestUtil { check.beginTree(astToVisit); check.visitToken(astToVisit); check.beginTree(null); - final Optional<Field> classField = Arrays.stream(check.getClass().getDeclaredFields()) - .filter(field -> fieldName.equals(field.getName())).findFirst(); - final Field resultField; - if (classField.isPresent()) { - resultField = classField.get(); - } - else { - resultField = check.getClass().getSuperclass().getDeclaredField(fieldName); - } - resultField.setAccessible(true); + final Field resultField = getClassDeclaredField(check.getClass(), fieldName); return isClear.test(resultField.get(check)); } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java index ba72c98c5..1840a8370 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java @@ -37,7 +37,10 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -/** @noinspection ClassOnlyUsedInOnePackage */ +/** + * XdocUtil. + * @noinspection ClassOnlyUsedInOnePackage + */ public final class XdocUtil { public static final String DIRECTORY_PATH = "src/xdocs"; diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java index 9b36a443e..3a4897805 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java @@ -34,7 +34,10 @@ import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -/** @noinspection ClassOnlyUsedInOnePackage */ +/** + * XmlUtil. + * @noinspection ClassOnlyUsedInOnePackage + */ public final class XmlUtil { private XmlUtil() { } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java index bedab2ef3..c2e78ebb7 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java @@ -29,6 +29,7 @@ import net.sf.saxon.sxpath.XPathExpression; import net.sf.saxon.trans.XPathException; /** + * XpathUtil. * @noinspection ClassOnlyUsedInOnePackage */ public final class XpathUtil { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java index 090b2d3b8..a000ea583 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java @@ -173,6 +173,7 @@ public class AnnotationUtilityTest { final DetailAST annotationName = new DetailAST(); annotations.setType(TokenTypes.ANNOTATIONS); annotation.setType(TokenTypes.ANNOTATION); + annotationNameHolder.setType(TokenTypes.AT); annotationName.setText("Annotation"); annotationNameHolder.setNextSibling(annotationName); @@ -184,4 +185,31 @@ public class AnnotationUtilityTest { assertTrue("Annotation should contain " + astForTest, AnnotationUtility.containsAnnotation(astForTest, "Annotation")); } + + @Test + public void testContainsAnnotationWithComment() { + final DetailAST astForTest = new DetailAST(); + astForTest.setType(TokenTypes.PACKAGE_DEF); + final DetailAST child = new DetailAST(); + final DetailAST annotations = new DetailAST(); + final DetailAST annotation = new DetailAST(); + final DetailAST annotationNameHolder = new DetailAST(); + final DetailAST annotationName = new DetailAST(); + final DetailAST comment = new DetailAST(); + annotations.setType(TokenTypes.ANNOTATIONS); + annotation.setType(TokenTypes.ANNOTATION); + annotationNameHolder.setType(TokenTypes.AT); + comment.setType(TokenTypes.BLOCK_COMMENT_BEGIN); + annotationName.setText("Annotation"); + + annotationNameHolder.setNextSibling(annotationName); + annotation.setFirstChild(comment); + comment.setNextSibling(annotationNameHolder); + annotations.setFirstChild(annotation); + child.setNextSibling(annotations); + astForTest.setFirstChild(child); + + assertTrue("Annotation should contain " + astForTest, + AnnotationUtility.containsAnnotation(astForTest, "Annotation")); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java index 0c8df797a..d82a70c6b 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java @@ -20,6 +20,7 @@ package com.puppycrawl.tools.checkstyle.utils; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.File; import java.util.Arrays; @@ -36,12 +37,18 @@ import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; public class BlockCommentPositionTest extends AbstractPathTestSupport { @Test + public void testPrivateConstr() throws Exception { + assertTrue("Constructor is not private", + TestUtil.isUtilsClassHasPrivateConstructor(BlockCommentPosition.class, true)); + } + + @Test public void testJavaDocsRecognition() throws Exception { final List<BlockCommentPositionTestMetadata> metadataList = Arrays.asList( new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnClass.java", BlockCommentPosition::isOnClass, 3), new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnMethod.java", - BlockCommentPosition::isOnMethod, 3), + BlockCommentPosition::isOnMethod, 4), new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnField.java", BlockCommentPosition::isOnField, 3), new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnEnum.java", @@ -53,7 +60,10 @@ public class BlockCommentPositionTest extends AbstractPathTestSupport { new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnAnnotation.java", BlockCommentPosition::isOnAnnotationDef, 3), new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnEnumMember.java", - BlockCommentPosition::isOnEnumConstant, 2) + BlockCommentPosition::isOnEnumConstant, 2), + new BlockCommentPositionTestMetadata( + "InputBlockCommentPositionOnAnnotationField.java", + BlockCommentPosition::isOnAnnotationField, 4) ); for (BlockCommentPositionTestMetadata metadata : metadataList) { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java index abdde4a4c..59f2fe019 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java @@ -186,23 +186,23 @@ public class CheckUtilsTest extends AbstractPathTestSupport { @Test public void testGetTypeParameterNames() throws Exception { - final DetailAST parameterisedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF); + final DetailAST parameterizedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF); final List<String> expected = Arrays.asList("V", "C"); assertEquals("Invalid type parameters", - expected, CheckUtils.getTypeParameterNames(parameterisedClassNode)); + expected, CheckUtils.getTypeParameterNames(parameterizedClassNode)); } @Test public void testGetTypeParameters() throws Exception { - final DetailAST parameterisedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF); + final DetailAST parameterizedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF); final DetailAST firstTypeParameter = - getNode(parameterisedClassNode, TokenTypes.TYPE_PARAMETER); + getNode(parameterizedClassNode, TokenTypes.TYPE_PARAMETER); final List<DetailAST> expected = Arrays.asList(firstTypeParameter, firstTypeParameter.getNextSibling().getNextSibling()); assertEquals("Invalid type parameters", expected, - CheckUtils.getTypeParameters(parameterisedClassNode)); + CheckUtils.getTypeParameters(parameterizedClassNode)); } @Test @@ -235,7 +235,7 @@ public class CheckUtilsTest extends AbstractPathTestSupport { } @Test - public void testIsNonViodMethod() throws Exception { + public void testIsNonVoidMethod() throws Exception { final DetailAST nonVoidMethod = getNodeFromFile(TokenTypes.METHOD_DEF); final DetailAST voidMethod = nonVoidMethod.getNextSibling(); @@ -276,13 +276,13 @@ public class CheckUtilsTest extends AbstractPathTestSupport { final DetailAST publicVariable = protectedVariable.getNextSibling(); final DetailAST packageVariable = publicVariable.getNextSibling(); - assertEquals("Invalid access modofier", AccessModifier.PRIVATE, + assertEquals("Invalid access modifier", AccessModifier.PRIVATE, CheckUtils.getAccessModifierFromModifiersToken(privateVariable.getFirstChild())); - assertEquals("Invalid access modofier", AccessModifier.PROTECTED, + assertEquals("Invalid access modifier", AccessModifier.PROTECTED, CheckUtils.getAccessModifierFromModifiersToken(protectedVariable.getFirstChild())); - assertEquals("Invalid access modofier", AccessModifier.PUBLIC, + assertEquals("Invalid access modifier", AccessModifier.PUBLIC, CheckUtils.getAccessModifierFromModifiersToken(publicVariable.getFirstChild())); - assertEquals("Invalid access modofier", AccessModifier.PACKAGE, + assertEquals("Invalid access modifier", AccessModifier.PACKAGE, CheckUtils.getAccessModifierFromModifiersToken(packageVariable.getFirstChild())); } @@ -310,6 +310,21 @@ public class CheckUtilsTest extends AbstractPathTestSupport { } @Test + public void testGetFirstNode2() { + final DetailAST child = new DetailAST(); + child.setLineNo(6); + child.setColumnNo(5); + + final DetailAST root = new DetailAST(); + root.setLineNo(5); + root.setColumnNo(6); + + root.addChild(child); + + assertEquals("Unexpected node", root, CheckUtils.getFirstNode(root)); + } + + @Test public void testIsReceiverParameter() throws Exception { final DetailAST objBlock = getNodeFromFile(TokenTypes.OBJBLOCK); final DetailAST methodWithReceiverParameter = objBlock.getLastChild().getPreviousSibling(); @@ -344,11 +359,14 @@ public class CheckUtilsTest extends AbstractPathTestSupport { @Test public void testParseClassNames() { - final String className = "I.am.class.name.with.dot.in.the.end."; - final Set<String> result = CheckUtils.parseClassNames(className); + final Set<String> actual = CheckUtils.parseClassNames( + "I.am.class.name.with.dot.in.the.end.", "ClassOnly", "my.Class"); final Set<String> expected = new HashSet<>(); - expected.add(className); - assertEquals("Result is not expected", expected, result); + expected.add("I.am.class.name.with.dot.in.the.end."); + expected.add("ClassOnly"); + expected.add("my.Class"); + expected.add("Class"); + assertEquals("Result is not expected", expected, actual); } private DetailAST getNodeFromFile(int type) throws Exception { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java index 1a7cfae54..52997d5df 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java @@ -92,6 +92,13 @@ public class CommonUtilsTest { } @Test + public void testCreatePattern() { + assertEquals("invalid pattern", "Test", CommonUtils.createPattern("Test").pattern()); + assertEquals("invalid pattern", ".*Pattern.*", CommonUtils.createPattern(".*Pattern.*") + .pattern()); + } + + @Test public void testBadRegex() { try { CommonUtils.createPattern("["); @@ -125,14 +132,14 @@ public class CommonUtilsTest { assertEquals("Invalid line number", 0, testCommentBlock.getLineNo()); final DetailAST contentCommentBlock = testCommentBlock.getFirstChild(); - assertEquals("Invalid tiken type", + assertEquals("Invalid token type", TokenTypes.COMMENT_CONTENT, contentCommentBlock.getType()); assertEquals("Invalid text", "*test_comment", contentCommentBlock.getText()); assertEquals("Invalid line number", 0, contentCommentBlock.getLineNo()); assertEquals("Invalid column number", -1, contentCommentBlock.getColumnNo()); final DetailAST endCommentBlock = contentCommentBlock.getNextSibling(); - assertEquals("Invalid tiken type", TokenTypes.BLOCK_COMMENT_END, endCommentBlock.getType()); + assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_END, endCommentBlock.getType()); assertEquals("Invalid text", "*/", endCommentBlock.getText()); } @@ -143,6 +150,8 @@ public class CommonUtilsTest { assertFalse("Invalid file extension", CommonUtils.matchesFileExtension(pdfFile, fileExtensions)); assertTrue("Invalid file extension", + CommonUtils.matchesFileExtension(pdfFile)); + assertTrue("Invalid file extension", CommonUtils.matchesFileExtension(pdfFile, (String[]) null)); final File javaFile = new File("file.java"); assertTrue("Invalid file extension", @@ -150,6 +159,20 @@ public class CommonUtilsTest { final File emptyExtensionFile = new File("file."); assertTrue("Invalid file extension", CommonUtils.matchesFileExtension(emptyExtensionFile, "")); + assertFalse("Invalid file extension", + CommonUtils.matchesFileExtension(pdfFile, ".noMatch")); + assertTrue("Invalid file extension", + CommonUtils.matchesFileExtension(pdfFile, ".pdf")); + } + + @Test + public void testHasWhitespaceBefore() { + assertTrue("Invalid result", + CommonUtils.hasWhitespaceBefore(0, "a")); + assertTrue("Invalid result", + CommonUtils.hasWhitespaceBefore(4, " a")); + assertFalse("Invalid result", + CommonUtils.hasWhitespaceBefore(5, " a")); } @Test @@ -206,7 +229,7 @@ public class CommonUtilsTest { } @Test - public void testGetNonExistingConstructor() { + public void testGetNonExistentConstructor() { try { CommonUtils.getConstructor(Math.class); fail("IllegalStateException is expected"); @@ -266,10 +289,36 @@ public class CommonUtilsTest { } @Test - public void testGetFileExtensionForFileNameWithoutExtension() { - final String fileNameWithoutExtension = "file"; - final String extension = CommonUtils.getFileExtension(fileNameWithoutExtension); - assertEquals("Invalid extension", "", extension); + public void testFillTemplateWithStringsByRegexp() { + assertEquals("invalid result", "template", CommonUtils.fillTemplateWithStringsByRegexp( + "template", "lineToPlaceInTemplate", Pattern.compile("NO MATCH"))); + assertEquals( + "invalid result", + "before word after", + CommonUtils.fillTemplateWithStringsByRegexp("before $0 after", "word", + Pattern.compile("\\w+"))); + assertEquals("invalid result", "before word 123 after1 word after2 123 after3", + CommonUtils.fillTemplateWithStringsByRegexp("before $0 after1 $1 after2 $2 after3", + "word 123", Pattern.compile("(\\w+) (\\d+)"))); + } + + @Test + public void testGetFileNameWithoutExtension() { + assertEquals("invalid result", "filename", + CommonUtils.getFileNameWithoutExtension("filename")); + assertEquals("invalid result", "filename", + CommonUtils.getFileNameWithoutExtension("filename.extension")); + assertEquals("invalid result", "filename.subext", + CommonUtils.getFileNameWithoutExtension("filename.subext.extension")); + } + + @Test + public void testGetFileExtension() { + assertEquals("Invalid extension", "", CommonUtils.getFileExtension("filename")); + assertEquals("Invalid extension", "extension", + CommonUtils.getFileExtension("filename.extension")); + assertEquals("Invalid extension", "extension", + CommonUtils.getFileExtension("filename.subext.extension")); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java index 4f29b3946..8b5b77365 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java @@ -58,9 +58,9 @@ public class FilterUtilsTest { } @Test - public void testNonExistingFile() { + public void testNonExistentFile() { assertFalse("Suppression file does not exist", - FilterUtils.isFileExists("non-existing.xml")); + FilterUtils.isFileExists("non-existent.xml")); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java index e03e7d2a1..4114b14e4 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java @@ -187,7 +187,7 @@ public class JavadocUtilsTest { @Test public void testEmptyJavadocComment() { final String emptyJavadocComment = "*"; - assertTrue("Should return true when empty jabadoc comment is passed", + assertTrue("Should return true when empty javadoc comment is passed", JavadocUtils.isJavadocComment(emptyJavadocComment)); } @@ -361,4 +361,11 @@ public class JavadocUtilsTest { assertEquals("Unexpected token name", "WBR_TAG", JavadocUtils.getTokenName(10079)); } + + @Test + public void testEscapeAllControlChars() { + assertEquals("invalid result", "abc", JavadocUtils.escapeAllControlChars("abc")); + assertEquals("invalid result", "1\\r2\\n3\\t", + JavadocUtils.escapeAllControlChars("1\\r2\\n3\\t")); + } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java index ed20df745..bfabf9372 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java @@ -87,9 +87,9 @@ public class ModuleReflectionUtilsTest { @Test public void testIsCheckstyleCheck() { assertTrue("Should return true when valid checkstyle check is passed", - ModuleReflectionUtils.isCheckstyleCheck(CheckClass.class)); + ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(CheckClass.class)); assertFalse("Should return false when invalid class is passed", - ModuleReflectionUtils.isCheckstyleCheck(NotCheckstyleCheck.class)); + ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(NotCheckstyleCheck.class)); } @Test @@ -147,16 +147,23 @@ public class ModuleReflectionUtilsTest { assertEquals("should use field", 1, test.getField()); } - /** @noinspection SuperClassHasFrequentlyUsedInheritors */ private static class ValidCheckstyleClass extends AutomaticBean { // empty, use default constructor + + @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } } private static class InvalidNonAutomaticBeanClass { // empty, use default constructor } - /** @noinspection AbstractClassNeverImplemented */ + /** + * AbstractInvalidClass. + * @noinspection AbstractClassNeverImplemented + */ private abstract static class AbstractInvalidClass extends AutomaticBean { public abstract void method(); } @@ -187,6 +194,11 @@ public class ModuleReflectionUtilsTest { private static class FilterClass extends AutomaticBean implements Filter { @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } + + @Override public boolean accept(AuditEvent event) { return false; } @@ -195,6 +207,11 @@ public class ModuleReflectionUtilsTest { private static class FileFilterModuleClass extends AutomaticBean implements BeforeExecutionFileFilter { @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } + + @Override public boolean accept(String uri) { return false; } @@ -202,6 +219,11 @@ public class ModuleReflectionUtilsTest { private static class RootModuleClass extends AutomaticBean implements RootModule { @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } + + @Override public void addListener(AuditListener listener) { //dummy method } @@ -224,6 +246,11 @@ public class ModuleReflectionUtilsTest { private static class TreeWalkerFilterClass extends AutomaticBean implements TreeWalkerFilter { @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } + + @Override public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) { return false; } @@ -232,6 +259,11 @@ public class ModuleReflectionUtilsTest { private static class AuditListenerClass extends AutomaticBean implements AuditListener { @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } + + @Override public void auditStarted(AuditEvent event) { //dummy method } @@ -285,5 +317,10 @@ public class ModuleReflectionUtilsTest { public int getField() { return field; } + + @Override + protected void finishLocalSetup() throws CheckstyleException { + //dummy method + } } } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java index d18b5884e..e7b46c3b9 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java @@ -39,51 +39,46 @@ public class ScopeUtilsTest { } @Test - public void testInEnumOnRoot() { + public void testInEnumBlock() { assertFalse("Should return false when passed is not enum", ScopeUtils.isInEnumBlock(new DetailAST())); - } - - @Test - public void testInEnumBlockInNew() { assertFalse("Should return false when passed is not enum", ScopeUtils.isInEnumBlock(getNode(TokenTypes.LITERAL_NEW, TokenTypes.MODIFIERS))); - } - - @Test - public void testInEnumBlockWithEnum() { assertTrue("Should return true when passed is enum", ScopeUtils.isInEnumBlock(getNode(TokenTypes.OBJBLOCK, TokenTypes.ENUM_DEF, TokenTypes.MODIFIERS))); - } - - @Test - public void testInEnumBlockInInterface() { assertFalse("Should return false when passed is not enum", - ScopeUtils.isInEnumBlock(getNode(TokenTypes.INTERFACE_DEF, + ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.MODIFIERS))); - } - - @Test - public void testInEnumBlockInAnnotation() { assertFalse("Should return false when passed is not enum", - ScopeUtils.isInEnumBlock(getNode(TokenTypes.ANNOTATION_DEF, + ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF, TokenTypes.MODIFIERS))); - } - - @Test - public void testInEnumBlockInClass() { assertFalse("Should return false when passed is not enum", - ScopeUtils.isInEnumBlock(getNode(TokenTypes.CLASS_DEF, + ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.CLASS_DEF, TokenTypes.MODIFIERS))); + assertFalse("Should return false when passed is not enum", + ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.LITERAL_NEW, + TokenTypes.IDENT))); + assertFalse("Should return false when passed is not expected", + ScopeUtils.isInEnumBlock(getNode(TokenTypes.PACKAGE_DEF, TokenTypes.DOT))); } @Test - public void testInEnumBlockInLiteralNew() { - assertFalse("Should return false when passed is not enum", - ScopeUtils.isInEnumBlock(getNode(TokenTypes.LITERAL_NEW, - TokenTypes.IDENT))); + public void testIsInCodeBlock() { + assertFalse("invalid result", ScopeUtils.isInCodeBlock(getNode(TokenTypes.CLASS_DEF))); + assertFalse("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.ASSIGN, TokenTypes.VARIABLE_DEF))); + assertTrue("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.METHOD_DEF, TokenTypes.OBJBLOCK))); + assertTrue("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.CTOR_DEF, TokenTypes.OBJBLOCK))); + assertTrue("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.INSTANCE_INIT, TokenTypes.OBJBLOCK))); + assertTrue("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.STATIC_INIT, TokenTypes.OBJBLOCK))); + assertTrue("invalid result", + ScopeUtils.isInCodeBlock(getNode(TokenTypes.LAMBDA, TokenTypes.ASSIGN))); } @Test @@ -113,6 +108,12 @@ public class ScopeUtilsTest { } @Test + public void testIsOuterMostTypePackageDef() { + assertTrue("Should return false when passed is not outer most type", + ScopeUtils.isOuterMostType(getNode(TokenTypes.PACKAGE_DEF, TokenTypes.DOT))); + } + + @Test public void testIsLocalVariableDefCatch() { assertTrue("Should return true when passed is variable def", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.LITERAL_CATCH, @@ -123,6 +124,26 @@ public class ScopeUtilsTest { public void testIsLocalVariableDefUnexpected() { assertFalse("Should return false when passed is not variable def", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.LITERAL_CATCH))); + assertFalse("Should return false when passed is not variable def", + ScopeUtils.isLocalVariableDef(getNode(TokenTypes.COMMA, TokenTypes.PARAMETER_DEF))); + } + + @Test + public void testIsLocalVariableDefResource() { + assertTrue("invalid result", + ScopeUtils.isLocalVariableDef(getNode(TokenTypes.RESOURCE))); + } + + @Test + public void testIsLocalVariableDefVariable() { + assertTrue("invalid result", + ScopeUtils.isLocalVariableDef(getNode(TokenTypes.SLIST, TokenTypes.VARIABLE_DEF))); + assertTrue("invalid result", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.FOR_INIT, + TokenTypes.VARIABLE_DEF))); + assertTrue("invalid result", ScopeUtils.isLocalVariableDef(getNode( + TokenTypes.FOR_EACH_CLAUSE, TokenTypes.VARIABLE_DEF))); + assertFalse("invalid result", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.CLASS_DEF, + TokenTypes.VARIABLE_DEF))); } @Test @@ -130,6 +151,11 @@ public class ScopeUtilsTest { assertTrue("Should return true when passed is class field def", ScopeUtils.isClassFieldDef(getNode(TokenTypes.CLASS_DEF, TokenTypes.OBJBLOCK, TokenTypes.VARIABLE_DEF))); + assertFalse("Should return false when passed is unexpected", + ScopeUtils.isClassFieldDef(getNode(TokenTypes.CLASS_DEF))); + assertFalse("Should return false when passed is method variable def", + ScopeUtils.isClassFieldDef(getNode(TokenTypes.METHOD_DEF, + TokenTypes.SLIST, TokenTypes.VARIABLE_DEF))); } @Test diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java index c1a0d97c8..474479f87 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java @@ -145,7 +145,7 @@ public class TokenUtilsTest { @Test public void testTokenIdIncorrect() { - final String id = "NON_EXISTING_VALUE"; + final String id = "NON_EXISTENT_VALUE"; try { TokenUtils.getTokenId(id); fail("IllegalArgumentException is expected"); @@ -158,7 +158,7 @@ public class TokenUtilsTest { @Test public void testShortDescriptionIncorrect() { - final String id = "NON_EXISTING_VALUE"; + final String id = "NON_EXISTENT_VALUE"; try { TokenUtils.getShortDescription(id); fail("IllegalArgumentException is expected"); @@ -184,7 +184,7 @@ public class TokenUtilsTest { } @Test - public void tetsGetTokenTypesTotalNumber() { + public void testGetTokenTypesTotalNumber() { final int tokenTypesTotalNumber = TokenUtils.getTokenTypesTotalNumber(); assertEquals("Invalid token total number", 169, tokenTypesTotalNumber); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java index 2cc154b74..4a3abf01e 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java @@ -111,7 +111,7 @@ public class XpathMapperTest extends AbstractPathTestSupport { @Test public void testAttributeOr() throws Exception { - final String xpath = "//METHOD_DEF[@text='getSomeMethod' or @text='nonExistingMethod']"; + final String xpath = "//METHOD_DEF[@text='getSomeMethod' or @text='nonExistentMethod']"; final RootNode rootNode = getRootNode("InputXpathMapperAst.java"); final DetailAST[] actual = convertToArray(getXpathItems(xpath, rootNode)); final DetailAST expectedClassDefNode = getSiblingByType(rootNode.getUnderlyingNode(), @@ -413,7 +413,7 @@ public class XpathMapperTest extends AbstractPathTestSupport { } @Test - public void testQueryNonExistingAttribute() throws Exception { + public void testQueryNonExistentAttribute() throws Exception { final String xpath = "/CLASS_DEF[@text='InputXpathMapperAst']"; final RootNode rootNode = getRootNode("InputXpathMapperAst.java"); final List<Item> nodes = getXpathItems(xpath, rootNode); @@ -450,7 +450,7 @@ public class XpathMapperTest extends AbstractPathTestSupport { } @Test - public void testQueryNonExistingAnnotation() throws Exception { + public void testQueryNonExistentAnnotation() throws Exception { final String xpath = "//ANNOTATION[@text='SpringBootApplication']"; final RootNode rootNode = getRootNode("InputXpathMapperAnnotation.java"); final List<Item> nodes = getXpathItems(xpath, rootNode); |