diff --git a/.ci/pitest.sh b/.ci/pitest.sh
index 023dc9aff07..122857b8fa1 100755
--- a/.ci/pitest.sh
+++ b/.ci/pitest.sh
@@ -34,6 +34,7 @@ case $1 in
pitest-annotation|pitest-design \
|pitest-metrics|pitest-modifier|pitest-naming \
|pitest-sizes|pitest-whitespace \
+|pitest-packagenamesloader \
|pitest-common-2)
mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
declare -a ignoredItems=();
@@ -74,9 +75,7 @@ pitest-header)
mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
declare -a ignoredItems=(
"AbstractHeaderCheck.java.html:
catch (final IOException ex) { | "
- "AbstractHeaderCheck.java.html: catch (final IOException ex) { | "
"AbstractHeaderCheck.java.html: throw new IllegalArgumentException("unable to load header", ex); | "
- "AbstractHeaderCheck.java.html: throw new CheckstyleException( | "
"HeaderCheck.java.html: if (list.length == 0) { | "
"RegexpHeaderCheck.java.html: if (list.length == 0) { | "
"RegexpHeaderCheck.java.html: isMatch = headerLineNo == headerSize | "
@@ -94,10 +93,6 @@ pitest-filters)
"SuppressionCommentFilter.java.html: if (line == object.line) { | "
"SuppressionXpathSingleFilter.java.html: if (checks == null) { | "
"SuppressionXpathSingleFilter.java.html: if (files == null) { | "
- "SuppressionsLoader.java.html: catch (final FileNotFoundException ex) { | "
- "SuppressionsLoader.java.html: catch (final IOException ex) { | "
- "SuppressionsLoader.java.html: throw new CheckstyleException("Unable to read " + sourceName, ex); | "
- "SuppressionsLoader.java.html: throw new CheckstyleException(UNABLE_TO_FIND_ERROR_MESSAGE + sourceName, ex); | "
"SuppressWithNearbyCommentFilter.java.html: else if (tagMessageRegexp == null) { | "
"SuppressWithNearbyCommentFilter.java.html: if (CommonUtil.startsWithChar(format, '+')) { | "
"SuppressWithNearbyCommentFilter.java.html: if (event.getLocalizedMessage() != null) { | "
@@ -126,11 +121,6 @@ pitest-api)
"FileContents.java.html: if (hasIntersection) { | "
"FileText.java.html: if (lineBreaks == null) { | "
"FileText.java.html: if (lineNo < lineBreakPositions.length) { | "
- "LocalizedMessage.java.html: StandardCharsets.UTF_8.name())) { | "
- "LocalizedMessage.java.html: resourceBundle = new PropertyResourceBundle(streamReader); | "
- "LocalizedMessage.java.html: connection.setUseCaches(!reload); | "
- "LocalizedMessage.java.html: if (connection != null) { | "
- "LocalizedMessage.java.html: if (url != null) { | "
);
checkPitestReport "${ignoredItems[@]}"
;;
@@ -138,8 +128,6 @@ pitest-api)
pitest-main)
mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
declare -a ignoredItems=(
- "Main.java.html: if (files != null) { | "
- "Main.java.html: else if (node.isFile()) { | "
"Main.java.html: if (node.canRead()) { | "
"Main.java.html: if (options.executeIgnoredModules) { | "
"Main.java.html: if (outputPath == null) { | "
@@ -337,15 +325,6 @@ pitest-tree-walker)
pitest-misc)
mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
declare -a ignoredItems=(
- "NewlineAtEndOfFileCheck.java.html: if (readBytes != len) { | "
- "NewlineAtEndOfFileCheck.java.html: throw new IOException("Unable to read " + len + " bytes, got " | "
- "SuppressWarningsHolder.java.html: .getLastColumn() >= column; | "
- "SuppressWarningsHolder.java.html: ALL_WARNING_MATCHING_ID.equals(entry.getCheckName()) | "
- "SuppressWarningsHolder.java.html: && (column == 0 || entry.getFirstColumn() <= column); | "
- "SuppressWarningsHolder.java.html: return firstColumn; | "
- "SuppressWarningsHolder.java.html: || entry.getFirstLine() == line | "
- "SuppressWarningsHolder.java.html: || entry.getLastLine() == line && entry | "
- "SuppressWarningsHolder.java.html: return entry.getFirstLine() < line | "
"TranslationCheck.java.html: if (exception instanceof NoSuchFileException) { | "
"TranslationCheck.java.html: args = null; | "
"TranslationCheck.java.html: key = "general.fileNotFound"; | "
@@ -364,45 +343,6 @@ pitest-utils)
checkPitestReport "${ignoredItems[@]}"
;;
-pitest-packagenamesloader)
- mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
- declare -a ignoredItems=(
- "PackageNamesLoader.java.html: while (packageFiles.hasMoreElements()) { | "
- "PackageNamesLoader.java.html: private final Deque<String> packageStack = new ArrayDeque<>(); | "
- "PackageNamesLoader.java.html: buf.append('.'); | "
- "PackageNamesLoader.java.html: buf.append(subPackage); | "
- "PackageNamesLoader.java.html: final String name = attributes.getValue("name"); | "
- "PackageNamesLoader.java.html: final String subPackage = iterator.next(); | "
- "PackageNamesLoader.java.html: packageNames.add(getPackageName()); | "
- "PackageNamesLoader.java.html: packageStack.pop(); | "
- "PackageNamesLoader.java.html: catch (IOException ex) { | "
- "PackageNamesLoader.java.html: catch (IOException ex) { | "
- "PackageNamesLoader.java.html: catch (ParserConfigurationException | SAXException ex) { | "
- "PackageNamesLoader.java.html: final Iterator<String> iterator = packageStack.descendingIterator(); | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: } | "
- "PackageNamesLoader.java.html: processFile(packageFiles.nextElement(), namesLoader); | "
- "PackageNamesLoader.java.html: final InputSource source = new InputSource(stream); | "
- "PackageNamesLoader.java.html: if (!CommonUtil.endsWithChar(subPackage, '.') && iterator.hasNext()) { | "
- "PackageNamesLoader.java.html: namesLoader.parseInputSource(source); | "
- "PackageNamesLoader.java.html: packageStack.push(name); | "
- "PackageNamesLoader.java.html: throw new CheckstyleException("unable to get package file resources", ex); | "
- "PackageNamesLoader.java.html: throw new CheckstyleException("unable to open " + packageFile, ex); | "
- "PackageNamesLoader.java.html: throw new CheckstyleException("unable to open one of package files", ex); | "
- "PackageNamesLoader.java.html: final StringBuilder buf = new StringBuilder(256); | "
- "PackageNamesLoader.java.html: if (PACKAGE_ELEMENT_NAME.equals(qName)) { | "
- "PackageNamesLoader.java.html: if (PACKAGE_ELEMENT_NAME.equals(qName)) { | "
- "PackageNamesLoader.java.html: return buf.toString(); | "
- "PackageNamesLoader.java.html: try (InputStream stream = new BufferedInputStream(packageFile.openStream())) { | "
- "PackageNamesLoader.java.html: while (iterator.hasNext()) { | "
- );
- checkPitestReport "${ignoredItems[@]}"
- ;;
-
# pitesttyle-gui)
# mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
# # post validation is skipped, we do not test gui throughly
diff --git a/config/suppressions.xml b/config/suppressions.xml
index 628c2c33d5a..e20b5e6b6c1 100644
--- a/config/suppressions.xml
+++ b/config/suppressions.xml
@@ -79,7 +79,7 @@
files="(Checker|Main|CheckstyleAntTask|JavadocDetailNodeParser)\.java"/>
+ |TranslationCheckTest|LocalizedMessageTest)\.java"/>
diff --git a/pom.xml b/pom.xml
index dd65216ec87..6a083839446 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1827,7 +1827,7 @@
com.puppycrawl.tools.checkstyle.filters.SuppressWarningsFilterTest
100
- 98
+ 99
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
${pitest.plugin.threads}
@@ -2052,8 +2052,8 @@
*.Input*
- 97
- 96
+ 98
+ 97
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
${pitest.plugin.threads}
@@ -2553,8 +2553,8 @@
com.puppycrawl.tools.checkstyle.PackageNamesLoaderTest
- 32
- 20
+ 100
+ 100
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
${pitest.plugin.threads}
@@ -2729,7 +2729,7 @@
com.puppycrawl.tools.checkstyle.MainTest
100
- 98
+ 99
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
${pitest.plugin.threads}
@@ -2878,7 +2878,7 @@
*.Input*
99
- 98
+ 99
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
${pitest.plugin.threads}
@@ -2924,7 +2924,7 @@
*.Input*
- 99
+ 100
97
${pitest.plugin.timeout.factor}
${pitest.plugin.timeout.constant}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
index 9ee0dc55098..7d3b6d78131 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
@@ -49,6 +49,7 @@
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.rules.TemporaryFolder;
+import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
@@ -617,6 +618,67 @@ public void testExistingDirectoryWithViolations() throws Exception {
getPath(""));
}
+ /**
+ * Test doesn't need to be serialized.
+ * @noinspection SerializableInnerClassWithNonSerializableOuterClass
+ */
+ @Test
+ public void testListFilesNotFile() throws Exception {
+ final File fileMock = new File("") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public boolean canRead() {
+ return true;
+ }
+
+ @Override
+ public boolean isDirectory() {
+ return false;
+ }
+
+ @Override
+ public boolean isFile() {
+ return false;
+ }
+ };
+
+ final List result = Whitebox.invokeMethod(Main.class, "listFiles",
+ fileMock, new ArrayList());
+ assertEquals("Invalid result size", 0, result.size());
+ }
+
+ /**
+ * Test doesn't need to be serialized.
+ * @noinspection SerializableInnerClassWithNonSerializableOuterClass
+ */
+ @Test
+ public void testListFilesDirectoryWithNull() throws Exception {
+ final File[] nullResult = null;
+ final File fileMock = new File("") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public boolean canRead() {
+ return true;
+ }
+
+ @Override
+ public boolean isDirectory() {
+ return true;
+ }
+
+ @Override
+ public File[] listFiles() {
+ return nullResult;
+ }
+ };
+
+ final List result = Whitebox.invokeMethod(Main.class, "listFiles",
+ fileMock, new ArrayList());
+ assertEquals("Invalid result size", 0, result.size());
+ }
+
@Test
public void testFileReferenceDuringException() throws Exception {
exit.expectSystemExitWithStatus(-2);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
index 9cd008d8f09..efd97e00aee 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
@@ -20,15 +20,32 @@
package com.puppycrawl.tools.checkstyle;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
+import org.xml.sax.SAXException;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
/**
- * Enter a description of class PackageNamesLoaderTest.java.
+ * Custom class loader is needed to pass URLs to pretend these are loaded from the classpath
+ * though we can't add/change the files for testing. The class loader is nested in this class,
+ * so the custom class loader we are using is safe.
+ * @noinspection ClassLoaderInstantiation
*/
public class PackageNamesLoaderTest extends AbstractPathTestSupport {
@@ -47,4 +64,174 @@ public void testDefault()
packageNames.size());
}
+ @Test
+ public void testNoPackages() throws Exception {
+ final Set actualPackageNames = PackageNamesLoader
+ .getPackageNames(new TestUrlsClassLoader(Collections.emptyEnumeration()));
+
+ assertEquals("Invalid package names length.", 0, actualPackageNames.size());
+ }
+
+ @Test
+ public void testPackagesFile() throws Exception {
+ final Enumeration enumeration = Collections.enumeration(Collections.singleton(
+ new File(getPath("InputPackageNamesLoaderFile.xml")).toURI().toURL()));
+
+ final Set actualPackageNames = PackageNamesLoader
+ .getPackageNames(new TestUrlsClassLoader(enumeration));
+ final String[] expectedPackageNames = {
+ "com.puppycrawl.tools.checkstyle",
+ "com.puppycrawl.tools.checkstyle.checks",
+ "com.puppycrawl.tools.checkstyle.checks.annotation",
+ "com.puppycrawl.tools.checkstyle.checks.blocks",
+ "com.puppycrawl.tools.checkstyle.checks.coding",
+ "com.puppycrawl.tools.checkstyle.checks.design",
+ "com.puppycrawl.tools.checkstyle.checks.header",
+ "com.puppycrawl.tools.checkstyle.checks.imports",
+ "com.puppycrawl.tools.checkstyle.checks.indentation",
+ "com.puppycrawl.tools.checkstyle.checks.javadoc",
+ "com.puppycrawl.tools.checkstyle.checks.metrics",
+ "com.puppycrawl.tools.checkstyle.checks.modifier",
+ "com.puppycrawl.tools.checkstyle.checks.naming",
+ "com.puppycrawl.tools.checkstyle.checks.regexp",
+ "com.puppycrawl.tools.checkstyle.checks.sizes",
+ "com.puppycrawl.tools.checkstyle.checks.whitespace",
+ "com.puppycrawl.tools.checkstyle.filefilters",
+ "com.puppycrawl.tools.checkstyle.filters",
+ };
+
+ assertEquals("Invalid package names length.", expectedPackageNames.length,
+ actualPackageNames.size());
+ final Set checkstylePackagesSet =
+ new HashSet<>(Arrays.asList(expectedPackageNames));
+ assertEquals("Invalid names set.", checkstylePackagesSet, actualPackageNames);
+ }
+
+ @Test
+ public void testPackagesWithDots() throws Exception {
+ final Enumeration enumeration = Collections.enumeration(Collections.singleton(
+ new File(getPath("InputPackageNamesLoaderWithDots.xml")).toURI().toURL()));
+
+ final Set actualPackageNames = PackageNamesLoader
+ .getPackageNames(new TestUrlsClassLoader(enumeration));
+ final String[] expectedPackageNames = {
+ "coding.",
+ };
+
+ assertEquals("Invalid package names length.", expectedPackageNames.length,
+ actualPackageNames.size());
+ final Set checkstylePackagesSet =
+ new HashSet<>(Arrays.asList(expectedPackageNames));
+ assertEquals("Invalid names set.", checkstylePackagesSet, actualPackageNames);
+ }
+
+ @Test
+ public void testPackagesWithDotsEx() throws Exception {
+ final Enumeration enumeration = Collections.enumeration(Collections.singleton(
+ new File(getPath("InputPackageNamesLoaderWithDotsEx.xml")).toURI().toURL()));
+
+ final Set actualPackageNames = PackageNamesLoader
+ .getPackageNames(new TestUrlsClassLoader(enumeration));
+ final String[] expectedPackageNames = {
+ "coding.specific",
+ "coding.",
+ };
+
+ assertEquals("Invalid package names length.", expectedPackageNames.length,
+ actualPackageNames.size());
+ final Set checkstylePackagesSet =
+ new HashSet<>(Arrays.asList(expectedPackageNames));
+ assertEquals("Invalid names set.", checkstylePackagesSet, actualPackageNames);
+ }
+
+ @Test
+ public void testPackagesWithSaxException() throws Exception {
+ final Enumeration enumeration = Collections.enumeration(Collections.singleton(
+ new File(getPath("InputPackageNamesLoaderNotXml.java")).toURI().toURL()));
+
+ try {
+ PackageNamesLoader.getPackageNames(new TestUrlsClassLoader(enumeration));
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ assertTrue("Invalid exception cause class", ex.getCause() instanceof SAXException);
+ }
+ }
+
+ @Test
+ public void testPackagesWithIoException() throws Exception {
+ final URLConnection urlConnection = new URLConnection(null) {
+ @Override
+ public void connect() {
+ // no code
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return null;
+ }
+ };
+ final URL url = new URL("test", null, 0, "", new URLStreamHandler() {
+ @Override
+ protected URLConnection openConnection(URL u) {
+ return urlConnection;
+ }
+ });
+
+ final Enumeration enumeration = Collections.enumeration(Collections.singleton(url));
+
+ try {
+ PackageNamesLoader.getPackageNames(new TestUrlsClassLoader(enumeration));
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ assertTrue("Invalid exception cause class", ex.getCause() instanceof IOException);
+ assertNotEquals("Invalid exception message",
+ "unable to get package file resources", ex.getMessage());
+ }
+ }
+
+ @Test
+ public void testPackagesWithIoExceptionGetResources() {
+ try {
+ PackageNamesLoader.getPackageNames(new TestIoExceptionClassLoader());
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ assertTrue("Invalid exception cause class", ex.getCause() instanceof IOException);
+ assertEquals("Invalid exception message",
+ "unable to get package file resources", ex.getMessage());
+ }
+ }
+
+ /**
+ * Custom class loader is needed to pass URLs to pretend these are loaded from the classpath
+ * though we can't add/change the files for testing.
+ * @noinspection CustomClassloader
+ */
+ private static class TestUrlsClassLoader extends ClassLoader {
+
+ private final Enumeration urls;
+
+ TestUrlsClassLoader(Enumeration urls) {
+ this.urls = urls;
+ }
+
+ @Override
+ public Enumeration getResources(String name) {
+ return urls;
+ }
+ }
+
+ /**
+ * Custom class loader is needed to throw an exception to test a catch statement.
+ * @noinspection CustomClassloader
+ */
+ private static class TestIoExceptionClassLoader extends ClassLoader {
+ @Override
+ public Enumeration getResources(String name) throws IOException {
+ throw new IOException("test");
+ }
+ }
+
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java
index 4d80c71a219..dd116ab92f6 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java
@@ -21,13 +21,20 @@
import static com.puppycrawl.tools.checkstyle.utils.CommonUtil.EMPTY_OBJECT_ARRAY;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.Test;
@@ -36,6 +43,12 @@
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.EqualsVerifierReport;
+/**
+ * Custom class loader is needed to pass URLs to pretend these are loaded from the classpath
+ * though we can't add/change the files for testing. The class loader is nested in this class,
+ * so the custom class loader we are using is safe.
+ * @noinspection ClassLoaderInstantiation
+ */
public class LocalizedMessageTest {
private static final Locale DEFAULT_LOCALE = Locale.getDefault();
@@ -72,6 +85,117 @@ public void testBundleReloadUrlNull() throws IOException {
assertNull("Bundle should be null when reload is true and URL is null", bundle);
}
+ /**
+ * Ignore resource errors for testing.
+ * @noinspection resource, IOResourceOpenedButNotSafelyClosed
+ */
+ @Test
+ public void testBundleReloadUrlNotNull() throws IOException {
+ final AtomicBoolean closed = new AtomicBoolean();
+
+ final InputStream inputStream = new InputStream() {
+ @Override
+ public int read() {
+ return -1;
+ }
+
+ @Override
+ public void close() {
+ closed.set(true);
+ }
+ };
+ final URLConnection urlConnection = new URLConnection(null) {
+ @Override
+ public void connect() {
+ // no code
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return inputStream;
+ }
+ };
+ final URL url = new URL("test", null, 0, "", new URLStreamHandler() {
+ @Override
+ protected URLConnection openConnection(URL u) {
+ return urlConnection;
+ }
+ });
+
+ final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control();
+ final ResourceBundle bundle = control.newBundle(
+ "com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH,
+ "java.class", new TestUrlsClassLoader(url), true);
+
+ assertNotNull("Bundle should not be null when stream is not null", bundle);
+ assertFalse("connection should not be using caches", urlConnection.getUseCaches());
+ assertTrue("connection should be closed", closed.get());
+ }
+
+ /**
+ * Ignore resource errors for testing.
+ * @noinspection resource, IOResourceOpenedButNotSafelyClosed
+ */
+ @Test
+ public void testBundleReloadUrlNotNullFalseReload() throws IOException {
+ final AtomicBoolean closed = new AtomicBoolean();
+
+ final InputStream inputStream = new InputStream() {
+ @Override
+ public int read() {
+ return -1;
+ }
+
+ @Override
+ public void close() {
+ closed.set(true);
+ }
+ };
+ final URLConnection urlConnection = new URLConnection(null) {
+ @Override
+ public void connect() {
+ // no code
+ }
+
+ @Override
+ public InputStream getInputStream() {
+ return inputStream;
+ }
+ };
+ final URL url = new URL("test", null, 0, "", new URLStreamHandler() {
+ @Override
+ protected URLConnection openConnection(URL u) {
+ return urlConnection;
+ }
+ });
+
+ final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control();
+ final ResourceBundle bundle = control.newBundle(
+ "com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH,
+ "java.class", new TestUrlsClassLoader(url), false);
+
+ assertNotNull("Bundle should not be null when stream is not null", bundle);
+ assertTrue("connection should not be using caches", urlConnection.getUseCaches());
+ assertTrue("connection should be closed", closed.get());
+ }
+
+ @Test
+ public void testBundleReloadUrlNotNullStreamNull() throws IOException {
+ final URL url = new URL("test", null, 0, "", new URLStreamHandler() {
+ @Override
+ protected URLConnection openConnection(URL u) {
+ return null;
+ }
+ });
+
+ final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control();
+ final ResourceBundle bundle = control.newBundle(
+ "com.puppycrawl.tools.checkstyle.checks.coding.messages",
+ Locale.ENGLISH, "java.class",
+ new TestUrlsClassLoader(url), true);
+ assertNull("Bundle should be null when stream is null", bundle);
+ }
+
@Test
public void testMessageInFrench() {
final LocalizedMessage localizedMessage = createSampleLocalizedMessage();
@@ -191,4 +315,23 @@ public void tearDown() {
LocalizedMessage.setLocale(DEFAULT_LOCALE);
}
+ /**
+ * Custom class loader is needed to pass URLs to pretend these are loaded from the classpath
+ * though we can't add/change the files for testing.
+ * @noinspection CustomClassloader
+ */
+ private static class TestUrlsClassLoader extends ClassLoader {
+
+ private final URL url;
+
+ TestUrlsClassLoader(URL url) {
+ this.url = url;
+ }
+
+ @Override
+ public URL getResource(String name) {
+ return url;
+ }
+ }
+
}
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 31c44a5d77f..c5212ddd5e4 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
@@ -21,17 +21,21 @@
import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF;
import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_UNABLE_OPEN;
+import static java.util.Locale.ENGLISH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.junit.Test;
+import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
@@ -194,4 +198,30 @@ public void testWrongFile() throws Exception {
getCheckMessage(MSG_KEY_UNABLE_OPEN, ""), iterator.next().getMessage());
}
+ @Test
+ public void testWrongSeparatorLength() throws Exception {
+ final RandomAccessFile file = new RandomAccessFile(
+ getPath("InputNewlineAtEndOfFileLf.java"), "r") {
+ @Override
+ public int read(byte[] bytes) {
+ return 0;
+ }
+ };
+
+ try {
+ Whitebox.invokeMethod(new NewlineAtEndOfFileCheck(), "endsWithNewline", file);
+ fail("Exception is expected");
+ }
+ catch (IOException ex) {
+ if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) {
+ assertEquals("Error message is unexpected",
+ "Unable to read 2 bytes, got 0", ex.getMessage());
+ }
+ else {
+ assertEquals("Error message is unexpected",
+ "Unable to read 1 bytes, got 0", ex.getMessage());
+ }
+ }
+ }
+
}
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 b9911dc2ec6..d4de553c0f1 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
@@ -21,24 +21,33 @@
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
+import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import org.junit.After;
import org.junit.Test;
+import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
+import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.JavaParser;
import com.puppycrawl.tools.checkstyle.TreeWalker;
+import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.Configuration;
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.checks.naming.MemberNameCheck;
import com.puppycrawl.tools.checkstyle.checks.whitespace.AbstractParenPadCheck;
import com.puppycrawl.tools.checkstyle.checks.whitespace.TypecastParenPadCheck;
import com.puppycrawl.tools.checkstyle.filters.SuppressWarningsFilter;
@@ -52,6 +61,17 @@ protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/suppresswarningsholder";
}
+ @After
+ public void cleanUp() {
+ // clear cache that may have been set by tests
+
+ new SuppressWarningsHolder().beginTree(null);
+
+ final Map map = Whitebox.getInternalState(SuppressWarningsHolder.class,
+ "CHECK_ALIAS_MAP");
+ map.clear();
+ }
+
@Test
public void testGet() {
final SuppressWarningsHolder checkObj = new SuppressWarningsHolder();
@@ -151,6 +171,83 @@ public void testSetAliasListWrong() {
}
}
+ @Test
+ public void testIsSuppressed() throws Exception {
+ populateHolder("MockEntry", 100, 100, 350, 350);
+ final AuditEvent event = createAuditEvent("check", 100, 10);
+
+ assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedByName() throws Exception {
+ populateHolder("check", 100, 100, 350, 350);
+ final SuppressWarningsHolder holder = new SuppressWarningsHolder();
+ final AuditEvent event = createAuditEvent("id", 110, 10);
+ holder.setAliasList(MemberNameCheck.class.getName() + "=check");
+
+ assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedByModuleId() throws Exception {
+ populateHolder("check", 100, 100, 350, 350);
+ final AuditEvent event = createAuditEvent("check", 350, 350);
+
+ assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedAfterEventEnd() throws Exception {
+ populateHolder("check", 100, 100, 350, 350);
+ final AuditEvent event = createAuditEvent("check", 350, 352);
+
+ assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedAfterEventEnd2() throws Exception {
+ populateHolder("check", 100, 100, 350, 350);
+ final AuditEvent event = createAuditEvent("check", 400, 10);
+
+ assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedAfterEventStart() throws Exception {
+ populateHolder("check", 100, 100, 350, 350);
+ final AuditEvent event = createAuditEvent("check", 100, 100);
+
+ assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
+ }
+
+ @Test
+ public void testIsSuppressedWithAllArgument() throws Exception {
+ populateHolder("all", 100, 100, 350, 350);
+
+ final Checker source = new Checker();
+ final LocalizedMessage firstMessageForTest =
+ new LocalizedMessage(100, 10, null, null, null, "id", MemberNameCheck.class, "msg");
+ final AuditEvent firstEventForTest =
+ new AuditEvent(source, "fileName", firstMessageForTest);
+ assertFalse("Event is suppressed",
+ SuppressWarningsHolder.isSuppressed(firstEventForTest));
+
+ final LocalizedMessage secondMessageForTest =
+ new LocalizedMessage(100, 150, null, null, null, "id", MemberNameCheck.class, "msg");
+ final AuditEvent secondEventForTest =
+ new AuditEvent(source, "fileName", secondMessageForTest);
+ assertTrue("Event is not suppressed",
+ SuppressWarningsHolder.isSuppressed(secondEventForTest));
+
+ final LocalizedMessage thirdMessageForTest =
+ new LocalizedMessage(200, 1, null, null, null, "id", MemberNameCheck.class, "msg");
+ final AuditEvent thirdEventForTest =
+ new AuditEvent(source, "fileName", thirdMessageForTest);
+ assertTrue("Event is not suppressed",
+ SuppressWarningsHolder.isSuppressed(thirdEventForTest));
+ }
+
@Test
public void testAnnotationInTry() throws Exception {
final Configuration checkConfig = createModuleConfig(SuppressWarningsHolder.class);
@@ -302,4 +399,28 @@ public void testClearState() throws Exception {
entries -> ((ThreadLocal>) entries).get().isEmpty()));
}
+ private static void populateHolder(String checkName, int firstLine,
+ int firstColumn, int lastLine,
+ int lastColumn) throws Exception {
+ final Class> entry = Class
+ .forName("com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder$Entry");
+ final Constructor> entryConstr = entry.getDeclaredConstructor(String.class, int.class,
+ int.class, int.class, int.class);
+ entryConstr.setAccessible(true);
+
+ final Object entryInstance = entryConstr.newInstance(checkName, firstLine,
+ firstColumn, lastLine, lastColumn);
+
+ final ThreadLocal> entries = Whitebox
+ .getInternalState(SuppressWarningsHolder.class, "ENTRIES");
+ entries.get().add(entryInstance);
+ }
+
+ private static AuditEvent createAuditEvent(String moduleId, int line, int column) {
+ final Checker source = new Checker();
+ final LocalizedMessage message = new LocalizedMessage(line, column, null, null, null,
+ moduleId, MemberNameCheck.class, "message");
+ return new AuditEvent(source, "filename", message);
+ }
+
}
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 a2b3b5618d0..f48beeb41d9 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
@@ -193,6 +193,21 @@ public void testSetHeaderTwice() {
}
}
+ @Test
+ public void testIoExceptionWhenLoadingHeaderFile() throws Exception {
+ final HeaderCheck check = new HeaderCheck();
+ check.setHeaderFile(new URI("test://bad"));
+
+ try {
+ Whitebox.invokeMethod(check, "loadHeaderFile");
+ fail("Exception expected");
+ }
+ catch (CheckstyleException ex) {
+ assertTrue("Invalid exception cause message",
+ ex.getMessage().startsWith("unable to load header file "));
+ }
+ }
+
@Test
public void testCacheHeaderFile() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class);
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 251f949095f..e39c98f8fe7 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
@@ -31,6 +31,7 @@
import org.junit.Test;
import org.powermock.reflect.Whitebox;
+import org.xml.sax.InputSource;
import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
import com.puppycrawl.tools.checkstyle.TreeWalkerFilter;
@@ -218,6 +219,36 @@ private static boolean isUrlReachable(String url) {
return result;
}
+ @Test
+ public void testUnableToFindSuppressions() throws Exception {
+ final String sourceName = "InputSuppressionsLoaderNone.xml";
+
+ try {
+ Whitebox.invokeMethod(SuppressionsLoader.class, "loadSuppressions",
+ new InputSource(sourceName), sourceName);
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ assertEquals("Invalid exception message", "Unable to find: " + sourceName,
+ ex.getMessage());
+ }
+ }
+
+ @Test
+ public void testUnableToReadSuppressions() throws Exception {
+ final String sourceName = "InputSuppressionsLoaderNone.xml";
+
+ try {
+ Whitebox.invokeMethod(SuppressionsLoader.class, "loadSuppressions",
+ new InputSource(), sourceName);
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ assertEquals("Invalid exception message", "Unable to read " + sourceName,
+ ex.getMessage());
+ }
+ }
+
@Test
public void testNoCheckNoId() throws IOException {
final String fn = getPath("InputSuppressionsLoaderNoCheckAndId.xml");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java
index d797b758388..08d2496764f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java
@@ -25,8 +25,6 @@
import static org.mockito.ArgumentMatchers.any;
import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,11 +33,9 @@
import org.powermock.modules.junit4.PowerMockRunner;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
-import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.checks.header.AbstractHeaderCheck;
import com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck;
import com.puppycrawl.tools.checkstyle.checks.header.HeaderCheckTest;
-import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ HeaderCheck.class, HeaderCheckTest.class, AbstractHeaderCheck.class })
@@ -50,6 +46,11 @@ protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/header/header";
}
+ /**
+ * This test needs powermock because {@code StringReader} can't throw an exception to trigger
+ * the catch otherwise unless the reader is mishandled.
+ * @throws Exception if there is an error.
+ */
@Test
public void testIoExceptionWhenLoadingHeader() throws Exception {
final HeaderCheck check = PowerMockito.spy(new HeaderCheck());
@@ -66,25 +67,4 @@ public void testIoExceptionWhenLoadingHeader() throws Exception {
}
}
- @Test
- public void testIoExceptionWhenLoadingHeaderFile() throws Exception {
- final HeaderCheck check = PowerMockito.spy(new HeaderCheck());
- PowerMockito.doThrow(new IOException("expected exception")).when(check, "loadHeader",
- any());
-
- check.setHeaderFile(CommonUtil.getUriByFilename(getPath("InputHeaderRegexp.java")));
-
- final Method loadHeaderFile = AbstractHeaderCheck.class.getDeclaredMethod("loadHeaderFile");
- loadHeaderFile.setAccessible(true);
- try {
- loadHeaderFile.invoke(check);
- fail("Exception expected");
- }
- catch (InvocationTargetException ex) {
- assertTrue("Invalid exception cause", ex.getCause() instanceof CheckstyleException);
- assertTrue("Invalid exception cause message",
- ex.getCause().getMessage().startsWith("unable to load header file "));
- }
- }
-
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/LocalizedMessagePowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/LocalizedMessagePowerTest.java
deleted file mode 100644
index a2923693ddc..00000000000
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/LocalizedMessagePowerTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-////////////////////////////////////////////////////////////////////////////////
-// checkstyle: Checks Java source code for adherence to a set of rules.
-// Copyright (C) 2001-2019 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.internal.powermock;
-
-import static org.junit.Assert.assertNull;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.powermock.api.mockito.PowerMockito.mock;
-import static org.powermock.api.mockito.PowerMockito.when;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.util.Locale;
-import java.util.ResourceBundle;
-
-import org.junit.Test;
-
-import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
-
-public class LocalizedMessagePowerTest {
-
- @Test
- public void testBundleReloadUrlNotNull() throws IOException {
- final ClassLoader classloader = mock(ClassLoader.class);
- final String resource =
- "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties";
- final URLConnection mockUrlCon = mock(URLConnection.class);
- final URLStreamHandler stubUrlHandler = new URLStreamHandler() {
- @Override
- protected URLConnection openConnection(URL u) {
- return mockUrlCon;
- }
- };
- final URL url = new URL("foo", "bar", 99, "/foobar", stubUrlHandler);
- final InputStream inputStreamMock = mock(InputStream.class);
- when(classloader.getResource(resource)).thenReturn(url);
- when(mockUrlCon.getInputStream()).thenReturn(inputStreamMock);
- when(inputStreamMock.read(any(), anyInt(), anyInt())).thenReturn(-1);
-
- final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control();
- control.newBundle("com.puppycrawl.tools.checkstyle.checks.coding.messages",
- Locale.ENGLISH, "java.class",
- classloader, true);
-
- verify(mockUrlCon, times(1)).setUseCaches(false);
- verify(inputStreamMock, times(1)).close();
- }
-
- @Test
- public void testBundleReloadUrlNotNullStreamNull() throws IOException {
- final ClassLoader classloader = mock(ClassLoader.class);
- final String resource =
- "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties";
-
- final URL url = getMockUrl(null);
- when(classloader.getResource(resource)).thenReturn(url);
-
- final LocalizedMessage.Utf8Control control = new LocalizedMessage.Utf8Control();
- final ResourceBundle bundle = control.newBundle(
- "com.puppycrawl.tools.checkstyle.checks.coding.messages",
- Locale.ENGLISH, "java.class",
- classloader, true);
- assertNull("Bundle should be null when stream is null", bundle);
- }
-
- private static URL getMockUrl(final URLConnection connection) throws IOException {
- final URLStreamHandler handler = new URLStreamHandler() {
- @Override
- protected URLConnection openConnection(final URL url) {
- return connection;
- }
- };
- return new URL("http://foo.bar", "foo.bar", 80, "", handler);
- }
-
-}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/MainPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/MainPowerTest.java
index 2deca080b78..fb50172a40c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/MainPowerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/MainPowerTest.java
@@ -20,16 +20,9 @@
package com.puppycrawl.tools.checkstyle.internal.powermock;
import static org.junit.Assert.assertEquals;
-import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
-import static org.powermock.api.mockito.PowerMockito.when;
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Locale;
-import java.util.regex.Pattern;
import org.junit.Rule;
import org.junit.Test;
@@ -74,38 +67,4 @@ public void testJacocoWorkaround() throws Exception {
assertEquals("Unexpected system error log", expected, systemErr.getLog());
}
- @Test
- @SuppressWarnings("unchecked")
- public void testListFilesNotFile() throws Exception {
- final Class> optionsClass = Class.forName(Main.class.getName());
- final Method method = optionsClass.getDeclaredMethod("listFiles", File.class, List.class);
- method.setAccessible(true);
-
- final File fileMock = mock(File.class);
- when(fileMock.canRead()).thenReturn(true);
- when(fileMock.isDirectory()).thenReturn(false);
- when(fileMock.isFile()).thenReturn(false);
-
- final List result = (List) method.invoke(null, fileMock,
- new ArrayList());
- assertEquals("Invalid result size", 0, result.size());
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testListFilesDirectoryWithNull() throws Exception {
- final Class> optionsClass = Class.forName(Main.class.getName());
- final Method method = optionsClass.getDeclaredMethod("listFiles", File.class, List.class);
- method.setAccessible(true);
-
- final File fileMock = mock(File.class);
- when(fileMock.canRead()).thenReturn(true);
- when(fileMock.isDirectory()).thenReturn(true);
- when(fileMock.listFiles()).thenReturn(null);
-
- final List result = (List) method.invoke(null, fileMock,
- new ArrayList());
- assertEquals("Invalid result size", 0, result.size());
- }
-
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/NewlineAtEndOfFileCheckPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/NewlineAtEndOfFileCheckPowerTest.java
deleted file mode 100644
index 226075e6b42..00000000000
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/NewlineAtEndOfFileCheckPowerTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-////////////////////////////////////////////////////////////////////////////////
-// checkstyle: Checks Java source code for adherence to a set of rules.
-// Copyright (C) 2001-2019 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.internal.powermock;
-
-import static java.util.Locale.ENGLISH;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.powermock.api.mockito.PowerMockito.mock;
-import static org.powermock.api.mockito.PowerMockito.when;
-
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import org.junit.Test;
-
-import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
-import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
-import com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck;
-
-public class NewlineAtEndOfFileCheckPowerTest extends AbstractModuleTestSupport {
-
- @Override
- protected String getPackageLocation() {
- return "com/puppycrawl/tools/checkstyle/checks/newlineatendoffile";
- }
-
- @Test
- public void testWrongSeparatorLength() throws Exception {
- final NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck();
- final DefaultConfiguration checkConfig = createModuleConfig(NewlineAtEndOfFileCheck.class);
- check.configure(checkConfig);
-
- final Method method = NewlineAtEndOfFileCheck.class
- .getDeclaredMethod("endsWithNewline", RandomAccessFile.class);
- method.setAccessible(true);
- final RandomAccessFile file = mock(RandomAccessFile.class);
- when(file.length()).thenReturn(2_000_000L);
- try {
- method.invoke(new NewlineAtEndOfFileCheck(), file);
- fail("Exception is expected");
- }
- catch (InvocationTargetException ex) {
- assertTrue("Error type is unexpected",
- ex.getCause() instanceof IOException);
- if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) {
- assertEquals("Error message is unexpected",
- "Unable to read 2 bytes, got 0", ex.getCause().getMessage());
- }
- else {
- assertEquals("Error message is unexpected",
- "Unable to read 1 bytes, got 0", ex.getCause().getMessage());
- }
- }
- }
-
-}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageNamesLoaderPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageNamesLoaderPowerTest.java
deleted file mode 100644
index 2b66a124319..00000000000
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageNamesLoaderPowerTest.java
+++ /dev/null
@@ -1,241 +0,0 @@
-////////////////////////////////////////////////////////////////////////////////
-// checkstyle: Checks Java source code for adherence to a set of rules.
-// Copyright (C) 2001-2019 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.internal.powermock;
-
-import static com.puppycrawl.tools.checkstyle.utils.CommonUtil.EMPTY_BYTE_ARRAY;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.powermock.api.mockito.PowerMockito.mock;
-import static org.powermock.api.mockito.PowerMockito.when;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-
-import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
-import com.puppycrawl.tools.checkstyle.PackageNamesLoader;
-import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
-
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(PackageNamesLoader.class)
-public class PackageNamesLoaderPowerTest extends AbstractPathTestSupport {
-
- @Override
- protected String getPackageLocation() {
- return "com/puppycrawl/tools/checkstyle/packagenamesloader";
- }
-
- /**
- * Tests the loading of package names. This test needs mocking, because the package names would
- * have to be placed in {@literal checkstyle_packages.xml}, but this will affect every test,
- * which is undesired.
- *
- * @throws Exception if error occurs
- */
- @Test
- @SuppressWarnings("unchecked")
- public void testPackagesFile() throws Exception {
- final URLConnection mockConnection = Mockito.mock(URLConnection.class);
- when(mockConnection.getInputStream()).thenReturn(
- Files.newInputStream(Paths.get(getPath("InputPackageNamesLoaderFile.xml"))));
-
- final URL url = getMockUrl(mockConnection);
-
- final Enumeration enumeration = mock(Enumeration.class);
- when(enumeration.hasMoreElements()).thenReturn(true).thenReturn(false);
- when(enumeration.nextElement()).thenReturn(url);
-
- final ClassLoader classLoader = mock(ClassLoader.class);
- when(classLoader.getResources("checkstyle_packages.xml")).thenReturn(enumeration);
-
- final Set actualPackageNames = PackageNamesLoader.getPackageNames(classLoader);
- final String[] expectedPackageNames = {
- "com.puppycrawl.tools.checkstyle",
- "com.puppycrawl.tools.checkstyle.checks",
- "com.puppycrawl.tools.checkstyle.checks.annotation",
- "com.puppycrawl.tools.checkstyle.checks.blocks",
- "com.puppycrawl.tools.checkstyle.checks.coding",
- "com.puppycrawl.tools.checkstyle.checks.design",
- "com.puppycrawl.tools.checkstyle.checks.header",
- "com.puppycrawl.tools.checkstyle.checks.imports",
- "com.puppycrawl.tools.checkstyle.checks.indentation",
- "com.puppycrawl.tools.checkstyle.checks.javadoc",
- "com.puppycrawl.tools.checkstyle.checks.metrics",
- "com.puppycrawl.tools.checkstyle.checks.modifier",
- "com.puppycrawl.tools.checkstyle.checks.naming",
- "com.puppycrawl.tools.checkstyle.checks.regexp",
- "com.puppycrawl.tools.checkstyle.checks.sizes",
- "com.puppycrawl.tools.checkstyle.checks.whitespace",
- "com.puppycrawl.tools.checkstyle.filefilters",
- "com.puppycrawl.tools.checkstyle.filters",
- };
-
- assertEquals("Invalid package names length.", expectedPackageNames.length,
- actualPackageNames.size());
- final Set checkstylePackagesSet =
- new HashSet<>(Arrays.asList(expectedPackageNames));
- assertEquals("Invalid names set.", checkstylePackagesSet, actualPackageNames);
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testPackagesWithDots() throws Exception {
- final Constructor constructor =
- PackageNamesLoader.class.getDeclaredConstructor();
- constructor.setAccessible(true);
- final PackageNamesLoader loader = constructor.newInstance();
-
- final Attributes attributes = mock(Attributes.class);
- when(attributes.getValue("name")).thenReturn("coding.");
- loader.startElement("", "", "package", attributes);
- loader.endElement("", "", "package");
-
- final Field field = PackageNamesLoader.class.getDeclaredField("packageNames");
- field.setAccessible(true);
- final Set list = (Set) field.get(loader);
- assertEquals("Invalid package name", "coding.", list.iterator().next());
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testPackagesWithDotsEx() throws Exception {
- final Constructor constructor =
- PackageNamesLoader.class.getDeclaredConstructor();
- constructor.setAccessible(true);
- final PackageNamesLoader loader = constructor.newInstance();
-
- final Attributes attributes1 = mock(Attributes.class);
- when(attributes1.getValue("name")).thenReturn("coding.");
- final Attributes attributes2 = mock(Attributes.class);
- when(attributes2.getValue("name")).thenReturn("specific");
-
- loader.startElement("", "", "package", attributes1);
- loader.startElement("", "", "package", attributes2);
- loader.endElement("", "", "package");
- loader.endElement("", "", "package");
-
- final Field field = PackageNamesLoader.class.getDeclaredField("packageNames");
- field.setAccessible(true);
- final Set list = (Set) field.get(loader);
- assertEquals("Invalid list size", 2, list.size());
- final Iterator iterator = list.iterator();
- assertEquals("Invalid package name", "coding.specific", iterator.next());
- assertEquals("Invalid package name", "coding.", iterator.next());
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testPackagesWithSaxException() throws Exception {
- final URLConnection mockConnection = Mockito.mock(URLConnection.class);
- when(mockConnection.getInputStream()).thenReturn(
- new ByteArrayInputStream(EMPTY_BYTE_ARRAY));
-
- final URL url = getMockUrl(mockConnection);
-
- final Enumeration enumeration = mock(Enumeration.class);
- when(enumeration.hasMoreElements()).thenReturn(true);
- when(enumeration.nextElement()).thenReturn(url);
-
- final ClassLoader classLoader = mock(ClassLoader.class);
- when(classLoader.getResources("checkstyle_packages.xml")).thenReturn(enumeration);
-
- try {
- PackageNamesLoader.getPackageNames(classLoader);
- fail("CheckstyleException is expected");
- }
- catch (CheckstyleException ex) {
- assertTrue("Invalid exception cause class", ex.getCause() instanceof SAXException);
- }
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testPackagesWithIoException() throws Exception {
- final URLConnection mockConnection = Mockito.mock(URLConnection.class);
- when(mockConnection.getInputStream()).thenReturn(null);
-
- final URL url = getMockUrl(mockConnection);
-
- final Enumeration enumer = mock(Enumeration.class);
- when(enumer.hasMoreElements()).thenReturn(true);
- when(enumer.nextElement()).thenReturn(url);
-
- final ClassLoader classLoader = mock(ClassLoader.class);
- when(classLoader.getResources("checkstyle_packages.xml")).thenReturn(enumer);
-
- try {
- PackageNamesLoader.getPackageNames(classLoader);
- fail("CheckstyleException is expected");
- }
- catch (CheckstyleException ex) {
- assertTrue("Invalid exception cause class", ex.getCause() instanceof IOException);
- assertNotEquals("Invalid exception message",
- "unable to get package file resources", ex.getMessage());
- }
- }
-
- @Test
- public void testPackagesWithIoExceptionGetResources() throws Exception {
- final ClassLoader classLoader = mock(ClassLoader.class);
- when(classLoader.getResources("checkstyle_packages.xml")).thenThrow(IOException.class);
-
- try {
- PackageNamesLoader.getPackageNames(classLoader);
- fail("CheckstyleException is expected");
- }
- catch (CheckstyleException ex) {
- assertTrue("Invalid exception cause class", ex.getCause() instanceof IOException);
- assertEquals("Invalid exception message",
- "unable to get package file resources", ex.getMessage());
- }
- }
-
- private static URL getMockUrl(final URLConnection connection) throws IOException {
- final URLStreamHandler handler = new URLStreamHandler() {
- @Override
- protected URLConnection openConnection(final URL url) {
- return connection;
- }
- };
- return new URL("http://foo.bar", "foo.bar", 80, "", handler);
- }
-
-}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/SuppressWarningsHolderPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/SuppressWarningsHolderPowerTest.java
deleted file mode 100644
index 35157aeedb8..00000000000
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/SuppressWarningsHolderPowerTest.java
+++ /dev/null
@@ -1,155 +0,0 @@
-////////////////////////////////////////////////////////////////////////////////
-// checkstyle: Checks Java source code for adherence to a set of rules.
-// Copyright (C) 2001-2019 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.internal.powermock;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.powermock.api.mockito.PowerMockito.mock;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import com.puppycrawl.tools.checkstyle.Checker;
-import com.puppycrawl.tools.checkstyle.api.AuditEvent;
-import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
-import com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder;
-import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck;
-
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(SuppressWarningsHolder.class)
-public class SuppressWarningsHolderPowerTest {
-
- @Test
- public void testIsSuppressed() throws Exception {
- createHolder("MockEntry", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("check", 100, 10);
-
- assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedByName() throws Exception {
- final SuppressWarningsHolder holder = createHolder("check", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("id", 110, 10);
- holder.setAliasList(MemberNameCheck.class.getName() + "=check");
-
- assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedByModuleId() throws Exception {
- createHolder("check", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("check", 350, 350);
-
- assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedAfterEventEnd() throws Exception {
- createHolder("check", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("check", 350, 352);
-
- assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedAfterEventEnd2() throws Exception {
- createHolder("check", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("check", 400, 10);
-
- assertFalse("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedAfterEventStart() throws Exception {
- createHolder("check", 100, 100, 350, 350);
- final AuditEvent event = createAuditEvent("check", 100, 100);
-
- assertTrue("Event is not suppressed", SuppressWarningsHolder.isSuppressed(event));
- }
-
- @Test
- public void testIsSuppressedWithAllArgument() throws Exception {
- createHolder("all", 100, 100, 350, 350);
-
- final Checker source = new Checker();
- final LocalizedMessage firstMessageForTest =
- new LocalizedMessage(100, 10, null, null, null, "id", MemberNameCheck.class, "msg");
- final AuditEvent firstEventForTest =
- new AuditEvent(source, "fileName", firstMessageForTest);
- assertFalse("Event is suppressed",
- SuppressWarningsHolder.isSuppressed(firstEventForTest));
-
- final LocalizedMessage secondMessageForTest =
- new LocalizedMessage(100, 150, null, null, null, "id", MemberNameCheck.class, "msg");
- final AuditEvent secondEventForTest =
- new AuditEvent(source, "fileName", secondMessageForTest);
- assertTrue("Event is not suppressed",
- SuppressWarningsHolder.isSuppressed(secondEventForTest));
-
- final LocalizedMessage thirdMessageForTest =
- new LocalizedMessage(200, 1, null, null, null, "id", MemberNameCheck.class, "msg");
- final AuditEvent thirdEventForTest =
- new AuditEvent(source, "fileName", thirdMessageForTest);
- assertTrue("Event is not suppressed",
- SuppressWarningsHolder.isSuppressed(thirdEventForTest));
- }
-
- private static SuppressWarningsHolder createHolder(String checkName, int firstLine,
- int firstColumn, int lastLine,
- int lastColumn) throws Exception {
- final Class> entry = Class
- .forName("com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder$Entry");
- final Constructor> entryConstr = entry.getDeclaredConstructor(String.class, int.class,
- int.class, int.class, int.class);
- entryConstr.setAccessible(true);
-
- final Object entryInstance = entryConstr.newInstance(checkName, firstLine,
- firstColumn, lastLine, lastColumn);
-
- final List