diff --git a/config/import-control-test.xml b/config/import-control-test.xml
index 6a54fba0846a..0b46547b5905 100644
--- a/config/import-control-test.xml
+++ b/config/import-control-test.xml
@@ -7,6 +7,13 @@
+
+
+
+
+
+
diff --git a/config/suppressions.xml b/config/suppressions.xml
index 86c3cdbb1a0b..628c2c33d5a1 100644
--- a/config/suppressions.xml
+++ b/config/suppressions.xml
@@ -97,4 +97,6 @@
+
+
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java b/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
index 8dbef183d274..a62c08fdffce 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
@@ -57,7 +57,7 @@
* configuration has changed.
*
*/
-final class PropertyCacheFile {
+public final class PropertyCacheFile {
/**
* The property key to use for storing the hashcode of the
@@ -93,7 +93,7 @@ final class PropertyCacheFile {
* @param config the current configuration, not null
* @param fileName the cache file
*/
- PropertyCacheFile(Configuration config, String fileName) {
+ public PropertyCacheFile(Configuration config, String fileName) {
if (config == null) {
throw new IllegalArgumentException("config can not be null");
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
index 4e1cb7df6584..4bcc06143792 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
@@ -40,7 +40,7 @@
/**
* Responsible for loading the contents of an import control configuration file.
*/
-final class ImportControlLoader extends XmlLoader {
+public final class ImportControlLoader extends XmlLoader {
/** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID_1_0 =
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java
index 7dbd6ebac3ce..9dc9cb516866 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java
@@ -20,23 +20,16 @@
package com.puppycrawl.tools.checkstyle;
import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
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 org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(AuditEvent.class)
public class AuditEventDefaultFormatterTest {
@Test
@@ -65,38 +58,6 @@ public void testFormatFullyQualifiedModuleNameDoesNotContainCheckSuffix() {
assertEquals("Invalid format", expected, formatter.format(event));
}
- @Test
- public void testFormatModuleNameContainsCheckSuffix() {
- final AuditEvent mock = PowerMockito.mock(AuditEvent.class);
- when(mock.getSourceName()).thenReturn("TestModuleCheck");
- when(mock.getSeverityLevel()).thenReturn(SeverityLevel.WARNING);
- when(mock.getLine()).thenReturn(1);
- when(mock.getColumn()).thenReturn(1);
- when(mock.getMessage()).thenReturn("Mocked message.");
- when(mock.getFileName()).thenReturn("InputMockFile.java");
- final AuditEventFormatter formatter = new AuditEventDefaultFormatter();
-
- final String expected = "[WARN] InputMockFile.java:1:1: Mocked message. [TestModule]";
-
- assertEquals("Invalid format", expected, formatter.format(mock));
- }
-
- @Test
- public void testFormatModuleNameDoesNotContainCheckSuffix() {
- final AuditEvent mock = PowerMockito.mock(AuditEvent.class);
- when(mock.getSourceName()).thenReturn("TestModule");
- when(mock.getSeverityLevel()).thenReturn(SeverityLevel.WARNING);
- when(mock.getLine()).thenReturn(1);
- when(mock.getColumn()).thenReturn(1);
- when(mock.getMessage()).thenReturn("Mocked message.");
- when(mock.getFileName()).thenReturn("InputMockFile.java");
- final AuditEventFormatter formatter = new AuditEventDefaultFormatter();
-
- final String expected = "[WARN] InputMockFile.java:1:1: Mocked message. [TestModule]";
-
- assertEquals("Invalid format", expected, formatter.format(mock));
- }
-
@Test
public void testFormatModuleWithModuleId() {
final LocalizedMessage message = new LocalizedMessage(1, 1, null, null, null,
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
index 641bed4cb03c..2d53a38db812 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
@@ -23,21 +23,17 @@
import static com.puppycrawl.tools.checkstyle.DefaultLogger.AUDIT_FINISHED_MESSAGE;
import static com.puppycrawl.tools.checkstyle.DefaultLogger.AUDIT_STARTED_MESSAGE;
import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF;
-import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertArrayEquals;
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.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -62,7 +58,6 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.powermock.api.mockito.PowerMockito;
import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
@@ -661,152 +656,6 @@ public void testClearCacheWhenCacheFileIsNotSet() {
Whitebox.getInternalState(checker, "cacheFile"));
}
- @Test
- public void testCatchErrorInProcessFilesMethod() throws Exception {
- // The idea of the test is to satisfy coverage rate.
- // An Error indicates serious problems that a reasonable application should not try to
- // catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
- // we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
- // that is why we use PowerMockito to reproduce them.
- final File mock = PowerMockito.mock(File.class);
- // Assume that I/O error is happened when we try to invoke 'lastModified()' method.
- final String errorMessage = "Java Virtual Machine is broken"
- + " or has run out of resources necessary for it to continue operating.";
- final Error expectedError = new IOError(new InternalError(errorMessage));
- when(mock.lastModified()).thenThrow(expectedError);
- when(mock.getAbsolutePath()).thenReturn("testFile");
- final Checker checker = new Checker();
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- // -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
- catch (Error error) {
- assertThat("Error cause differs from IOError",
- error.getCause(), instanceOf(IOError.class));
- assertThat("Error cause is not InternalError",
- error.getCause().getCause(), instanceOf(InternalError.class));
- assertEquals("Error message is not expected",
- errorMessage, error.getCause().getCause().getMessage());
- }
- }
-
- @Test
- public void testCatchErrorWithNoFileName() throws Exception {
- // The idea of the test is to satisfy coverage rate.
- // An Error indicates serious problems that a reasonable application should not try to
- // catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
- // we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
- // that is why we use PowerMockito to reproduce them.
- final File mock = PowerMockito.mock(File.class);
- // Assume that I/O error is happened when we try to invoke 'lastModified()' method.
- final String errorMessage = "Java Virtual Machine is broken"
- + " or has run out of resources necessary for it to continue operating.";
- final Error expectedError = new IOError(new InternalError(errorMessage));
- when(mock.lastModified()).thenThrow(expectedError);
- final Checker checker = new Checker();
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- // -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
- catch (Error error) {
- assertThat("Error cause differs from IOError",
- error.getCause(), instanceOf(IOError.class));
- assertThat("Error cause is not InternalError",
- error.getCause().getCause(), instanceOf(InternalError.class));
- assertEquals("Error message is not expected",
- errorMessage, error.getCause().getCause().getMessage());
- }
- }
-
- @Test
- public void testCatchErrorWithCache() throws Exception {
- final File cacheFile = temporaryFolder.newFile();
-
- final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
- checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
- checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
-
- final File mock = PowerMockito.mock(File.class);
- final String errorMessage = "Java Virtual Machine is broken"
- + " or has run out of resources necessary for it to continue operating.";
- final Error expectedError = new IOError(new InternalError(errorMessage));
- when(mock.getAbsolutePath()).thenReturn("testFile");
- when(mock.getAbsoluteFile()).thenThrow(expectedError);
- final Checker checker = new Checker();
- checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
- checker.configure(checkerConfig);
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- // -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
- catch (Error error) {
- assertThat("Error cause differs from IOError",
- error.getCause(), instanceOf(IOError.class));
- assertEquals("Error message is not expected",
- errorMessage, error.getCause().getCause().getMessage());
-
- // destroy is called by Main
- checker.destroy();
-
- final Properties cache = new Properties();
- cache.load(Files.newBufferedReader(cacheFile.toPath()));
-
- assertEquals("Cache has unexpected size",
- 1, cache.size());
- assertNull("testFile is not in cache",
- cache.getProperty("testFile"));
- }
- }
-
- @Test
- public void testCatchErrorWithCacheWithNoFileName() throws Exception {
- final File cacheFile = temporaryFolder.newFile();
-
- final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
- checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
- checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
-
- final File mock = PowerMockito.mock(File.class);
- final String errorMessage = "Java Virtual Machine is broken"
- + " or has run out of resources necessary for it to continue operating.";
- final Error expectedError = new IOError(new InternalError(errorMessage));
- when(mock.getAbsolutePath()).thenThrow(expectedError);
- final Checker checker = new Checker();
- checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
- checker.configure(checkerConfig);
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- // -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
- catch (Error error) {
- assertThat("Error cause differs from IOError",
- error.getCause(), instanceOf(IOError.class));
- assertEquals("Error message is not expected",
- errorMessage, error.getCause().getCause().getMessage());
-
- // destroy is called by Main
- checker.destroy();
-
- final Properties cache = new Properties();
- cache.load(Files.newBufferedReader(cacheFile.toPath()));
-
- assertEquals("Cache has unexpected size",
- 1, cache.size());
- }
- }
-
/**
* It is OK to have long test method name here as it describes the test purpose.
*/
@@ -1029,75 +878,6 @@ public void testExceptionWithCache() throws Exception {
}
}
- @Test
- public void testExceptionWithNoFileName() {
- // The idea of the test is to satisfy coverage rate.
- // An Error indicates serious problems that a reasonable application should not try to
- // catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
- // we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
- // that is why we use PowerMockito to reproduce them.
- final File mock = PowerMockito.mock(File.class);
- final String errorMessage = "Security Exception";
- final Exception expectedError = new SecurityException(errorMessage);
- when(mock.getAbsolutePath()).thenThrow(expectedError);
- final Checker checker = new Checker();
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- catch (CheckstyleException ex) {
- assertThat("Error cause differs from SecurityException",
- ex.getCause(), instanceOf(SecurityException.class));
- assertEquals("Error message is not expected",
- errorMessage, ex.getCause().getMessage());
- }
- }
-
- @Test
- public void testExceptionWithCacheAndNoFileName() throws Exception {
- final File cacheFile = temporaryFolder.newFile();
-
- final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
- checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
- checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
-
- // The idea of the test is to satisfy coverage rate.
- // An Error indicates serious problems that a reasonable application should not try to
- // catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
- // we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
- // that is why we use PowerMockito to reproduce them.
- final File mock = PowerMockito.mock(File.class);
- final String errorMessage = "Security Exception";
- final Exception expectedError = new SecurityException(errorMessage);
- when(mock.getAbsolutePath()).thenThrow(expectedError);
- final Checker checker = new Checker();
- checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
- checker.configure(checkerConfig);
- final List filesToProcess = new ArrayList<>();
- filesToProcess.add(mock);
- try {
- checker.process(filesToProcess);
- fail("IOError is expected!");
- }
- catch (CheckstyleException ex) {
- assertThat("Error cause differs from SecurityException",
- ex.getCause(), instanceOf(SecurityException.class));
- assertEquals("Error message is not expected",
- errorMessage, ex.getCause().getMessage());
-
- // destroy is called by Main
- checker.destroy();
-
- final Properties cache = new Properties();
- cache.load(Files.newBufferedReader(cacheFile.toPath()));
-
- assertEquals("Cache has unexpected size",
- 1, cache.size());
- }
- }
-
@Test
public void testHaltOnExceptionOff() throws Exception {
final DefaultConfiguration checkConfig =
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
index 7687ba8a0033..3b2d2086494f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
@@ -23,10 +23,8 @@
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.powermock.api.mockito.PowerMockito.when;
import java.io.File;
-import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
@@ -36,12 +34,7 @@
import java.util.Properties;
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 org.powermock.reflect.Whitebox;
-import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
@@ -51,8 +44,6 @@
/**
* Unit test for ConfigurationLoader.
*/
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({DefaultConfiguration.class, ConfigurationLoader.class})
public class ConfigurationLoaderTest extends AbstractPathTestSupport {
@Override
@@ -457,38 +448,6 @@ public void testExternalEntityFromUri() throws Exception {
verifyConfigNode(config, "Checker", 2, atts);
}
- @Test
- public void testIncorrectTag() throws Exception {
- try {
- final Class> aClassParent = ConfigurationLoader.class;
- final Constructor> ctorParent = aClassParent.getDeclaredConstructor(
- PropertyResolver.class, boolean.class, ThreadModeSettings.class);
- ctorParent.setAccessible(true);
- final Object objParent = ctorParent.newInstance(null, true, null);
-
- final Class> aClass = Class.forName("com.puppycrawl.tools.checkstyle."
- + "ConfigurationLoader$InternalLoader");
- final Constructor> constructor = aClass.getConstructor(objParent.getClass());
- constructor.setAccessible(true);
-
- final Object obj = constructor.newInstance(objParent);
-
- final Class>[] param = new Class>[] {String.class, String.class,
- String.class, Attributes.class, };
- final Method method = aClass.getDeclaredMethod("startElement", param);
-
- method.invoke(obj, "", "", "hello", null);
-
- fail("Exception is expected");
- }
- catch (InvocationTargetException ex) {
- assertTrue("Invalid exception cause",
- ex.getCause() instanceof IllegalStateException);
- assertEquals("Invalid exception cause message",
- "Unknown name:" + "hello" + ".", ex.getCause().getMessage());
- }
- }
-
@Test
public void testNonExistentPropertyName() throws Exception {
try {
@@ -597,37 +556,6 @@ public void testLoadConfigurationFromClassPath() throws Exception {
0, children[0].getChildren().length);
}
- @Test
- public void testConfigWithIgnoreExceptionalAttributes() throws Exception {
- // emulate exception from unrelated code, but that is same try-catch
- final DefaultConfiguration tested = PowerMockito.mock(DefaultConfiguration.class);
- when(tested.getAttributeNames()).thenReturn(new String[] {"severity"});
- when(tested.getName()).thenReturn("MemberName");
- when(tested.getAttribute("severity")).thenThrow(CheckstyleException.class);
- // to void creation of 2 other mocks for now reason, only one moc is used for all cases
- PowerMockito.whenNew(DefaultConfiguration.class)
- .withArguments("MemberName", ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE)
- .thenReturn(tested);
- PowerMockito.whenNew(DefaultConfiguration.class)
- .withArguments("Checker", ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE)
- .thenReturn(tested);
- PowerMockito.whenNew(DefaultConfiguration.class)
- .withArguments("TreeWalker", ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE)
- .thenReturn(tested);
-
- try {
- ConfigurationLoader.loadConfiguration(
- getPath("InputConfigurationLoaderModuleIgnoreSeverity.xml"),
- new PropertiesExpander(new Properties()), true);
- fail("Exception is expected");
- }
- catch (CheckstyleException expected) {
- assertEquals("Invalid exception cause message",
- "Problem during accessing 'severity' attribute for MemberName",
- expected.getCause().getMessage());
- }
- }
-
@Test
public void testParsePropertyString() throws Exception {
final List propertyRefs = new ArrayList<>();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
index 5e61012233fe..952697bafdc0 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
@@ -23,9 +23,6 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
@@ -37,7 +34,6 @@
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
-import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
public class DefaultLoggerTest {
@@ -78,43 +74,6 @@ public void testCtorWithTwoParameters() {
output.contains("java.lang.IllegalStateException: upsss"));
}
- @Test
- public void testNewCtor() throws Exception {
- final OutputStream infoStream = spy(new ByteArrayOutputStream());
- final ByteArrayOutputStream errorStream = spy(new ByteArrayOutputStream());
- final DefaultLogger dl = new DefaultLogger(infoStream,
- AutomaticBean.OutputStreamOptions.CLOSE, errorStream,
- AutomaticBean.OutputStreamOptions.CLOSE);
- dl.auditStarted(null);
- dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss"));
- dl.auditFinished(new AuditEvent(6000, "myfile"));
- final String output = errorStream.toString(StandardCharsets.UTF_8.name());
- final LocalizedMessage addExceptionMessage = new LocalizedMessage(1,
- Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.ADD_EXCEPTION_MESSAGE,
- new String[] {"myfile"}, null,
- getClass(), null);
- final LocalizedMessage startMessage = new LocalizedMessage(1,
- Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.AUDIT_STARTED_MESSAGE,
- CommonUtil.EMPTY_STRING_ARRAY, null,
- getClass(), null);
- final LocalizedMessage finishMessage = new LocalizedMessage(1,
- Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.AUDIT_FINISHED_MESSAGE,
- CommonUtil.EMPTY_STRING_ARRAY, null,
- getClass(), null);
-
- verify(infoStream, times(1)).close();
- verify(errorStream, times(1)).close();
- final String infoOutput = infoStream.toString();
- assertTrue("Message should contain exception info, but was " + infoOutput,
- infoOutput.contains(startMessage.getMessage()));
- assertTrue("Message should contain exception info, but was " + infoOutput,
- infoOutput.contains(finishMessage.getMessage()));
- assertTrue("Message should contain exception info, but was " + output,
- output.contains(addExceptionMessage.getMessage()));
- assertTrue("Message should contain exception info, but was " + output,
- output.contains("java.lang.IllegalStateException: upsss"));
- }
-
@Test
public void testNewCtorWithTwoParameters() {
final OutputStream infoStream = new ByteArrayOutputStream();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
index 907872abcaec..9ee0dc550981 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
@@ -25,9 +25,6 @@
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.mockStatic;
-import static org.powermock.api.mockito.PowerMockito.when;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -52,9 +49,6 @@
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
@@ -62,10 +56,7 @@
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.internal.testmodules.TestRootModuleChecker;
-import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({Main.class, CommonUtil.class})
public class MainTest {
private static final String SHORT_USAGE = String.format(Locale.ROOT,
@@ -626,40 +617,6 @@ public void testExistingDirectoryWithViolations() throws Exception {
getPath(""));
}
- @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());
- }
-
@Test
public void testFileReferenceDuringException() throws Exception {
exit.expectSystemExitWithStatus(-2);
@@ -1414,23 +1371,6 @@ public void testModuleNameInMultiThreadMode() throws Exception {
}
}
- /**
- * This test is a workaround for the Jacoco limitations. A call to {@link System#exit(int)}
- * will never return, so Jacoco coverage probe will be missing. By mocking the {@code System}
- * class we turn {@code System.exit()} to noop and the Jacoco coverage probe should succeed.
- *
- * @throws Exception if error occurs
- * @see Jacoco issue 117
- */
- @Test
- public void testJacocoWorkaround() throws Exception {
- final String expected = "Missing required parameter: " + EOL + SHORT_USAGE;
- mockStatic(System.class);
- Main.main();
- assertEquals("Unexpected output log", "", systemOut.getLog());
- assertEquals("Unexpected system error log", expected, systemErr.getLog());
- }
-
@Test
public void testMissingFiles() throws Exception {
exit.expectSystemExitWithStatus(-1);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
index 4f850c557621..9cd008d8f094 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/PackageNamesLoaderTest.java
@@ -19,44 +19,17 @@
package com.puppycrawl.tools.checkstyle;
-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.api.CheckstyleException;
/**
* Enter a description of class PackageNamesLoaderTest.java.
*/
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(PackageNamesLoader.class)
public class PackageNamesLoaderTest extends AbstractPathTestSupport {
@Override
@@ -74,179 +47,4 @@ public void testDefault()
packageNames.size());
}
- /**
- * 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/PackageObjectFactoryTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java
index fa6a80657e64..6c6affe9bd71 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java
@@ -31,13 +31,9 @@
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.fail;
-import static org.powermock.api.mockito.PowerMockito.doThrow;
-import static org.powermock.api.mockito.PowerMockito.mockStatic;
import java.io.File;
-import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -49,12 +45,6 @@
import java.util.Set;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PowerMockIgnore;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
@@ -62,15 +52,11 @@
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck;
import com.puppycrawl.tools.checkstyle.internal.utils.CheckUtil;
-import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil;
/**
* Enter a description of class PackageObjectFactoryTest.java.
*
*/
-@RunWith(PowerMockRunner.class)
-@PowerMockIgnore(value = "com.puppycrawl.tools.checkstyle.api.*", globalIgnore = false)
-@PrepareForTest(ModuleReflectionUtil.class)
public class PackageObjectFactoryTest {
private final PackageObjectFactory factory = new PackageObjectFactory(
@@ -334,43 +320,6 @@ public void testCreateCheckWithPartialPackageNameByBruteForce() throws Exception
assertNotNull("Check should not be null when creating module from name", check);
}
- /**
- * This method is for testing the case of an exception caught inside
- * {@code PackageObjectFactory.generateThirdPartyNameToFullModuleName}, a private method used
- * to initialize private field {@code PackageObjectFactory.thirdPartyNameToFullModuleNames}.
- * Since the method and the field both are private, the {@link Whitebox} is required to ensure
- * that the field is changed. Also, the expected exception should be thrown from the static
- * method {@link ModuleReflectionUtil#getCheckstyleModules}, so {@link PowerMockito#mockStatic}
- * is required to mock this exception.
- *
- * @throws Exception when the code tested throws an exception
- */
- @Test
- public void testGenerateThirdPartyNameToFullModuleNameWithException() throws Exception {
- final String name = "String";
- final String packageName = "java.lang";
- final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- final Set packages = Collections.singleton(packageName);
- final PackageObjectFactory objectFactory = new PackageObjectFactory(packages, classLoader,
- TRY_IN_ALL_REGISTERED_PACKAGES);
-
- mockStatic(ModuleReflectionUtil.class);
- doThrow(new IOException("mock exception")).when(ModuleReflectionUtil.class);
- ModuleReflectionUtil.getCheckstyleModules(packages, classLoader);
-
- final String internalFieldName = "thirdPartyNameToFullModuleNames";
- final Map nullMap = Whitebox.getInternalState(objectFactory,
- internalFieldName);
- assertNull("Expected uninitialized field", nullMap);
-
- final Object instance = objectFactory.createModule(name);
- assertEquals("Expected empty string", "", instance);
-
- final Map emptyMap = Whitebox.getInternalState(objectFactory,
- internalFieldName);
- assertEquals("Expected empty map", Collections.emptyMap(), emptyMap);
- }
-
@Test
public void testJoinPackageNamesWithClassName() throws Exception {
final Class clazz = PackageObjectFactory.class;
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
index 8dc9efb329c1..e811fc0ac901 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
@@ -21,32 +21,20 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.times;
-import static org.powermock.api.mockito.PowerMockito.doNothing;
-import static org.powermock.api.mockito.PowerMockito.mockStatic;
-import static org.powermock.api.mockito.PowerMockito.verifyStatic;
-import static org.powermock.api.mockito.PowerMockito.when;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Properties;
@@ -55,22 +43,12 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentMatchers;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
-import com.google.common.io.Closeables;
-import com.google.common.io.Flushables;
-import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({ PropertyCacheFile.class, ByteStreams.class,
- CommonUtil.class, Closeables.class, Flushables.class})
public class PropertyCacheFileTest extends AbstractPathTestSupport {
@Rule
@@ -127,26 +105,6 @@ public void testResetIfFileDoesNotExist() throws IOException {
cache.get(PropertyCacheFile.CONFIG_HASH_KEY));
}
- @Test
- public void testCloseAndFlushOutputStreamAfterCreatingHashCode() throws IOException {
- mockStatic(Closeables.class);
- doNothing().when(Closeables.class);
- Closeables.close(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
- mockStatic(Flushables.class);
- doNothing().when(Flushables.class);
- Flushables.flush(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
-
- final Configuration config = new DefaultConfiguration("myName");
- final PropertyCacheFile cache = new PropertyCacheFile(config, "fileDoesNotExist.txt");
- cache.load();
-
- verifyStatic(Closeables.class, times(1));
- Closeables.close(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
-
- verifyStatic(Flushables.class, times(1));
- Flushables.flush(any(ObjectOutputStream.class), ArgumentMatchers.eq(false));
- }
-
@Test
public void testPopulateDetails() throws IOException {
final Configuration config = new DefaultConfiguration("myName");
@@ -262,64 +220,6 @@ public void testExternalResourceIsSavedInCache() throws Exception {
cache.get("module-resource*?:" + pathToResource));
}
- /**
- * This SuppressWarning("unchecked") required to suppress
- * "Unchecked generics array creation for varargs parameter" during mock.
- * @throws IOException when smth wrong with file creation or cache.load
- */
- @Test
- public void testNonExistentResource() throws IOException {
- final Configuration config = new DefaultConfiguration("myName");
- final String filePath = temporaryFolder.newFile().getPath();
- final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
-
- // create cache with one file
- cache.load();
- final String myFile = "myFile";
- cache.put(myFile, 1);
-
- final String hash = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
- assertNotNull("Config hash key should not be null", hash);
-
- mockStatic(ByteStreams.class);
-
- when(ByteStreams.toByteArray(any(BufferedInputStream.class)))
- .thenThrow(IOException.class);
-
- // apply new external resource to clear cache
- final Set resources = new HashSet<>();
- final String resource = getPath("InputPropertyCacheFile.header");
- resources.add(resource);
- cache.putExternalResources(resources);
-
- assertFalse("Should return false in file is not in cache",
- cache.isInCache(myFile, 1));
- assertFalse("Should return false in file is not in cache",
- cache.isInCache(resource, 1));
- }
-
- @Test
- public void testFlushAndCloseCacheFileOutputStream() throws IOException {
- mockStatic(Closeables.class);
- doNothing().when(Closeables.class);
- Closeables.close(any(OutputStream.class), ArgumentMatchers.eq(false));
- mockStatic(Flushables.class);
- doNothing().when(Flushables.class);
- Flushables.flush(any(OutputStream.class), ArgumentMatchers.eq(false));
-
- final Configuration config = new DefaultConfiguration("myName");
- final PropertyCacheFile cache = new PropertyCacheFile(config,
- temporaryFolder.newFile().getPath());
-
- cache.put("CheckedFileName.java", System.currentTimeMillis());
- cache.persist();
-
- verifyStatic(Closeables.class, times(1));
- Closeables.close(any(OutputStream.class), ArgumentMatchers.eq(false));
- verifyStatic(Flushables.class, times(1));
- Flushables.flush(any(OutputStream.class), ArgumentMatchers.eq(false));
- }
-
@Test
public void testCacheDirectoryDoesNotExistAndShouldBeCreated() throws IOException {
final Configuration config = new DefaultConfiguration("myName");
@@ -345,138 +245,6 @@ public void testPathToCacheContainsOnlyFileName() throws IOException {
Files.delete(Paths.get(filePath));
}
- @Test
- public void testExceptionNoSuchAlgorithmException() throws Exception {
- final Configuration config = new DefaultConfiguration("myName");
- final String filePath = temporaryFolder.newFile().getPath();
- final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
- cache.put("myFile", 1);
- mockStatic(MessageDigest.class);
-
- when(MessageDigest.getInstance("SHA-1"))
- .thenThrow(NoSuchAlgorithmException.class);
-
- final Class>[] param = new Class>[1];
- param[0] = Serializable.class;
- final Method method =
- PropertyCacheFile.class.getDeclaredMethod("getHashCodeBasedOnObjectContent", param);
- method.setAccessible(true);
- try {
- method.invoke(cache, config);
- fail("InvocationTargetException is expected");
- }
- catch (InvocationTargetException ex) {
- assertTrue("Invalid exception cause",
- ex.getCause().getCause() instanceof NoSuchAlgorithmException);
- assertEquals("Invalid exception message",
- "Unable to calculate hashcode.", ex.getCause().getMessage());
- }
- }
-
- @Test
- public void testPutNonExistentExternalResourceSameExceptionBetweenRuns() throws Exception {
- final File cacheFile = temporaryFolder.newFile();
-
- // We mock getUriByFilename method of CommonUtil to guarantee that it will
- // throw CheckstyleException with the specific content.
- mockStatic(CommonUtil.class);
- final CheckstyleException mockException =
- new CheckstyleException("Cannot get URL for cache file " + cacheFile.getAbsolutePath());
- when(CommonUtil.getUriByFilename(any(String.class)))
- .thenThrow(mockException);
-
- // We invoke 'putExternalResources' twice to invalidate cache
- // 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];
- for (int i = 0; i < numberOfRuns; i++) {
- final Configuration config = new DefaultConfiguration("myConfig");
- final PropertyCacheFile cache = new PropertyCacheFile(config, cacheFile.getPath());
- cache.load();
-
- configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
- assertNotNull("Config hash key should not be null", configHashes[i]);
-
- final Set 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);
- assertNotNull("External resource hashes should not be null",
- externalResourceHashes[i]);
-
- cache.persist();
-
- final Properties cacheDetails = new Properties();
- cacheDetails.load(Files.newBufferedReader(cacheFile.toPath()));
-
- final int expectedNumberOfObjectsInCacheFile = 2;
- assertEquals("Unexpected number of objects in cache",
- expectedNumberOfObjectsInCacheFile, cacheDetails.size());
- }
-
- assertEquals("Invalid config hash", configHashes[0], configHashes[1]);
- assertEquals("Invalid external resource hashes",
- externalResourceHashes[0], externalResourceHashes[1]);
- }
-
- /**
- * It is OK to have long test method name here as it describes the test purpose.
- */
- @Test
- public void testPutNonExistentExternalResourceDifferentExceptionsBetweenRuns()
- throws Exception {
- final File cacheFile = temporaryFolder.newFile();
-
- // We invoke 'putExternalResources' twice to invalidate cache
- // and have two different exceptions with different content.
- final int numberOfRuns = 2;
- final String[] configHashes = new String[numberOfRuns];
- final String[] externalResourceHashes = new String[numberOfRuns];
- for (int i = 0; i < numberOfRuns; i++) {
- final Configuration config = new DefaultConfiguration("myConfig");
- final PropertyCacheFile cache = new PropertyCacheFile(config, cacheFile.getPath());
-
- // We mock getUriByFilename method of CommonUtil to guarantee that it will
- // throw CheckstyleException with the specific content.
- mockStatic(CommonUtil.class);
- final CheckstyleException mockException = new CheckstyleException("Exception #" + i);
- when(CommonUtil.getUriByFilename(any(String.class)))
- .thenThrow(mockException);
-
- cache.load();
-
- configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
- assertNotNull("Config hash key should not be null", configHashes[i]);
-
- final Set 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);
- assertNotNull("External resource hashes should not be null",
- externalResourceHashes[i]);
-
- cache.persist();
-
- final Properties cacheDetails = new Properties();
- cacheDetails.load(Files.newBufferedReader(cacheFile.toPath()));
-
- final int expectedNumberOfObjectsInCacheFile = 2;
- assertEquals("Unexpected number of objects in cache",
- expectedNumberOfObjectsInCacheFile, cacheDetails.size());
- }
-
- assertEquals("Invalid config hash", configHashes[0], configHashes[1]);
- assertNotEquals("Invalid external resource hashes",
- externalResourceHashes[0], externalResourceHashes[1]);
- }
-
@Test
public void testChangeInConfig() throws Exception {
final DefaultConfiguration config = new DefaultConfiguration("myConfig");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java
index f8e39a28d997..3bc3038a5ac1 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java
@@ -23,10 +23,6 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.times;
-import static org.powermock.api.mockito.PowerMockito.spy;
-import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import java.io.File;
import java.io.Writer;
@@ -43,18 +39,13 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
import org.mockito.internal.util.Checks;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.Context;
-import com.puppycrawl.tools.checkstyle.api.DetailAST;
-import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.FileText;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck;
@@ -71,8 +62,6 @@
import com.puppycrawl.tools.checkstyle.filters.SuppressionXpathFilter;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(TreeWalker.class)
public class TreeWalkerTest extends AbstractModuleTestSupport {
@Rule
@@ -353,46 +342,6 @@ public void testBehaviourWithZeroChecks() throws Exception {
assertTrue("No checks -> No parsing", checks.isEmpty());
}
- @Test
- public void testBehaviourWithOnlyOrdinaryChecks() throws Exception {
- final TreeWalker treeWalkerSpy = spy(new TreeWalker());
- final Class> classAstState =
- Class.forName("com.puppycrawl.tools.checkstyle.TreeWalker$AstState");
- final PackageObjectFactory factory = new PackageObjectFactory(
- new HashSet<>(), Thread.currentThread().getContextClassLoader());
- treeWalkerSpy.configure(createModuleConfig(TypeNameCheck.class));
- treeWalkerSpy.setModuleFactory(factory);
- treeWalkerSpy.setupChild(createModuleConfig(TypeNameCheck.class));
- final File file = temporaryFolder.newFile("file.java");
- final List lines = new ArrayList<>();
- lines.add("class Test {}");
- treeWalkerSpy.processFiltered(file, new FileText(file, lines));
- verifyPrivate(treeWalkerSpy, times(1)).invoke("walk",
- any(DetailAST.class), any(FileContents.class), any(classAstState));
- verifyPrivate(treeWalkerSpy, times(0)).invoke("getFilteredMessages",
- any(String.class), any(FileContents.class), any(DetailAST.class));
- }
-
- @Test
- public void testBehaviourWithOnlyCommentChecks() throws Exception {
- final TreeWalker treeWalkerSpy = spy(new TreeWalker());
- final Class> classAstState =
- Class.forName("com.puppycrawl.tools.checkstyle.TreeWalker$AstState");
- final PackageObjectFactory factory = new PackageObjectFactory(
- new HashSet<>(), Thread.currentThread().getContextClassLoader());
- treeWalkerSpy.configure(createModuleConfig(CommentsIndentationCheck.class));
- treeWalkerSpy.setModuleFactory(factory);
- treeWalkerSpy.setupChild(createModuleConfig(CommentsIndentationCheck.class));
- final File file = temporaryFolder.newFile("file.java");
- final List lines = new ArrayList<>();
- lines.add("class Test {}");
- treeWalkerSpy.processFiltered(file, new FileText(file, lines));
- verifyPrivate(treeWalkerSpy, times(1)).invoke("walk",
- any(DetailAST.class), any(FileContents.class), any(classAstState));
- verifyPrivate(treeWalkerSpy, times(0)).invoke("getFilteredMessages",
- any(String.class), any(FileContents.class), any(DetailAST.class));
- }
-
@Test
public void testBehaviourWithOrdinaryAndCommentChecks() throws Exception {
final TreeWalker treeWalker = new TreeWalker();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListenerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListenerTest.java
index 472e681ef616..4a5bb0d2eab7 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListenerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListenerTest.java
@@ -22,13 +22,9 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
@@ -146,7 +142,7 @@ public void testAddException() {
}
@Test
- public void testCorrectOne() throws IOException {
+ public void testCorrectOne() {
final AuditEvent event = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
FIRST_MESSAGE);
@@ -169,7 +165,7 @@ public void testCorrectOne() throws IOException {
}
@Test
- public void testCorrectTwo() throws IOException {
+ public void testCorrectTwo() {
final AuditEvent event1 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
SECOND_MESSAGE);
@@ -199,7 +195,7 @@ public void testCorrectTwo() throws IOException {
}
@Test
- public void testOnlyOneMatching() throws IOException {
+ public void testOnlyOneMatching() {
final AuditEvent event1 = createAuditEvent("InputXpathFileGeneratorAuditListener.java",
10, 5, MethodParamPadCheck.class);
@@ -269,8 +265,8 @@ private static String getPath(String filename) {
+ filename;
}
- private static void verifyOutput(String expected, AuditEvent... events) throws IOException {
- final OutputStream out = spy(new ByteArrayOutputStream());
+ private static void verifyOutput(String expected, AuditEvent... events) {
+ final OutputStream out = new ByteArrayOutputStream();
final XpathFileGeneratorAuditListener listener =
new XpathFileGeneratorAuditListener(out, AutomaticBean.OutputStreamOptions.CLOSE);
@@ -280,9 +276,6 @@ private static void verifyOutput(String expected, AuditEvent... events) throws I
listener.auditFinished(null);
- verify(out, times(1)).flush();
- verify(out, times(1)).close();
-
final String actual = out.toString();
assertEquals("Invalid suppressions file content", expected, actual);
}
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 015c2c25300f..aaed92675001 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java
@@ -25,15 +25,12 @@
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.Mockito.when;
-import static org.powermock.api.mockito.PowerMockito.mockStatic;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -47,10 +44,6 @@
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.resources.FileResource;
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 org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
@@ -61,8 +54,6 @@
import com.puppycrawl.tools.checkstyle.internal.testmodules.CheckerStub;
import com.puppycrawl.tools.checkstyle.internal.testmodules.TestRootModuleChecker;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(CheckstyleAntTask.class)
public class CheckstyleAntTaskTest extends AbstractPathTestSupport {
private static final String FLAWLESS_INPUT =
@@ -148,16 +139,16 @@ public final void testPathsFileWithLogVerification() throws IOException {
antTask.execute();
// then
- final List loggedMessages = antTask.getLoggedMessages();
+ final List loggedMessages = antTask.getLoggedMessages();
assertEquals("Scanning path was not logged", 1, loggedMessages.stream().filter(
- msg -> msg.getMsg().startsWith("1) Scanning path")).count());
+ msg -> msg.startsWith("1) Scanning path")).count());
assertEquals("Scanning path was not logged", 1, loggedMessages.stream().filter(
- msg -> msg.getMsg().startsWith("1) Adding 1 files from path")).count());
+ msg -> msg.startsWith("1) Adding 1 files from path")).count());
assertEquals("Scanning empty was logged", 0, loggedMessages.stream().filter(
- msg -> msg.getMsg().startsWith("2) Adding 0 files from path ")).count());
+ msg -> msg.startsWith("2) Adding 0 files from path ")).count());
assertTrue("Checker is not processed",
TestRootModuleChecker.isProcessed());
@@ -638,9 +629,8 @@ public void testSetClasspath() {
antTask.setClasspath(new Path(project, path1));
antTask.setClasspath(new Path(project, path2));
- assertNotNull("Classpath should not be null",
- Whitebox.getInternalState(antTask, "classpath"));
final Path classpath = Whitebox.getInternalState(antTask, "classpath");
+ assertNotNull("Classpath should not be null", classpath);
assertTrue("Classpath contain provided path", classpath.toString().contains(path1));
assertTrue("Classpath contain provided path", classpath.toString().contains(path2));
}
@@ -729,90 +719,6 @@ public void testClassloaderInRootModule() throws IOException {
classLoader instanceof AntClassLoader);
}
- @Test
- public void testCheckerException() throws IOException {
- final CheckstyleAntTask antTask = new CheckstyleAntTaskStub();
- antTask.setConfig(getPath(CONFIG_FILE));
- antTask.setProject(new Project());
- antTask.setFile(new File(""));
- try {
- antTask.execute();
- fail("Exception is expected");
- }
- catch (BuildException ex) {
- assertTrue("Error message is unexpected",
- ex.getMessage().startsWith("Unable to process files:"));
- }
- }
-
- @Test
- public final void testExecuteLogOutput() throws Exception {
- final CheckstyleAntTaskLogStub antTask = new CheckstyleAntTaskLogStub();
- final URL url = new File(getPath(CONFIG_FILE)).toURI().toURL();
- antTask.setProject(new Project());
- antTask.setConfig(url.toString());
- antTask.setFile(new File(getPath(FLAWLESS_INPUT)));
-
- mockStatic(System.class);
- when(System.currentTimeMillis()).thenReturn(1L);
-
- antTask.execute();
-
- final LocalizedMessage auditStartedMessage = new LocalizedMessage(1,
- Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.auditStarted",
- null, null,
- getClass(), null);
- final LocalizedMessage auditFinishedMessage = new LocalizedMessage(1,
- Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.auditFinished",
- null, null,
- getClass(), null);
-
- final List expectedList = Arrays.asList(
- new MessageLevelPair("checkstyle version ", Project.MSG_VERBOSE),
- new MessageLevelPair("Adding standalone file for audit", Project.MSG_VERBOSE),
- new MessageLevelPair("To locate the files took 0 ms.", Project.MSG_VERBOSE),
- new MessageLevelPair("Running Checkstyle ", Project.MSG_INFO),
- new MessageLevelPair("Using configuration ", Project.MSG_VERBOSE),
- new MessageLevelPair(auditStartedMessage.getMessage(), Project.MSG_DEBUG),
- new MessageLevelPair(auditFinishedMessage.getMessage(), Project.MSG_DEBUG),
- new MessageLevelPair("To process the files took 0 ms.", Project.MSG_VERBOSE),
- new MessageLevelPair("Total execution took 0 ms.", Project.MSG_VERBOSE)
- );
-
- final List loggedMessages = antTask.getLoggedMessages();
-
- assertEquals("Amount of log messages is unexpected",
- expectedList.size(), loggedMessages.size());
- for (int i = 0; i < expectedList.size(); i++) {
- final MessageLevelPair expected = expectedList.get(i);
- final MessageLevelPair actual = loggedMessages.get(i);
- assertTrue("Log messages were expected",
- actual.getMsg().startsWith(expected.getMsg()));
- assertEquals("Log messages were expected",
- expected.getLevel(), actual.getLevel());
- }
- }
-
- /**
- * Non meaningful javadoc just to contain "noinspection" tag.
- * Till https://youtrack.jetbrains.com/issue/IDEA-187210
- * @noinspection JUnitTestCaseWithNoTests
- */
- private static class CheckstyleAntTaskStub extends CheckstyleAntTask {
-
- @Override
- protected List scanFileSets() {
- final File mock = PowerMockito.mock(File.class);
- // Assume that I/O error is happened when we try to invoke 'lastModified()' method.
- final Exception expectedError = new RuntimeException("");
- when(mock.lastModified()).thenThrow(expectedError);
- final List list = new ArrayList<>();
- list.add(mock);
- return list;
- }
-
- }
-
/**
* Non meaningful javadoc just to contain "noinspection" tag.
* Till https://youtrack.jetbrains.com/issue/IDEA-187210
@@ -820,47 +726,22 @@ protected List scanFileSets() {
*/
private static class CheckstyleAntTaskLogStub extends CheckstyleAntTask {
- private final List loggedMessages = new ArrayList<>();
+ private final List loggedMessages = new ArrayList<>();
@Override
public void log(String msg, int msgLevel) {
- loggedMessages.add(new MessageLevelPair(msg, msgLevel));
+ loggedMessages.add(msg);
}
@Override
public void log(String msg, Throwable t, int msgLevel) {
- loggedMessages.add(new MessageLevelPair(msg, msgLevel));
+ loggedMessages.add(msg);
}
- public List getLoggedMessages() {
+ public List getLoggedMessages() {
return Collections.unmodifiableList(loggedMessages);
}
}
- /**
- * Non meaningful javadoc just to contain "noinspection" tag.
- * Till https://youtrack.jetbrains.com/issue/IDEA-187210
- * @noinspection JUnitTestCaseWithNoTests
- */
- private static final class MessageLevelPair {
-
- private final String msg;
- private final int level;
-
- MessageLevelPair(String msg, int level) {
- this.msg = msg;
- this.level = level;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public int getLevel() {
- return level;
- }
-
- }
-
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractCheckTest.java
index fa9216c122c9..e5243e818f59 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractCheckTest.java
@@ -19,9 +19,8 @@
package com.puppycrawl.tools.checkstyle.api;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import java.io.File;
import java.nio.charset.Charset;
@@ -29,7 +28,6 @@
import java.util.HashMap;
import java.util.Map;
-import org.junit.Assert;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
@@ -61,7 +59,7 @@ public int[] getRequiredTokens() {
}
};
// Eventually it will become clear abstract method
- Assert.assertArrayEquals("Invalid number of tokens, should be empty",
+ assertArrayEquals("Invalid number of tokens, should be empty",
CommonUtil.EMPTY_INT_ARRAY, check.getRequiredTokens());
}
@@ -84,33 +82,17 @@ public int[] getRequiredTokens() {
}
};
// Eventually it will become clear abstract method
- Assert.assertArrayEquals("Invalid number of tokens, should be empty",
+ assertArrayEquals("Invalid number of tokens, should be empty",
CommonUtil.EMPTY_INT_ARRAY, check.getAcceptableTokens());
}
@Test
public void testVisitToken() {
- final AbstractCheck check = new AbstractCheck() {
- @Override
- public int[] getDefaultTokens() {
- return CommonUtil.EMPTY_INT_ARRAY;
- }
-
- @Override
- public int[] getAcceptableTokens() {
- return CommonUtil.EMPTY_INT_ARRAY;
- }
-
- @Override
- public int[] getRequiredTokens() {
- return CommonUtil.EMPTY_INT_ARRAY;
- }
- };
- final AbstractCheck checkSpy = spy(check);
+ final VisitCounterCheck check = new VisitCounterCheck();
// Eventually it will become clear abstract method
- checkSpy.visitToken(null);
+ check.visitToken(null);
- verify(checkSpy, times(1)).visitToken(null);
+ assertEquals("expected call count", 1, check.count);
}
@Test
@@ -135,7 +117,7 @@ public int[] getRequiredTokens() {
new File(getPath("InputAbstractCheckTestFileContents.java")),
Charset.defaultCharset().name())));
- Assert.assertEquals("Invalid line content", " * I'm a javadoc", check.getLine(3));
+ assertEquals("Invalid line content", " * I'm a javadoc", check.getLine(3));
}
@Test
@@ -159,7 +141,7 @@ public int[] getRequiredTokens() {
final int tabWidth = 4;
check.setTabWidth(tabWidth);
- Assert.assertEquals("Invalid tab width", tabWidth, check.getTabWidth());
+ assertEquals("Invalid tab width", tabWidth, check.getTabWidth());
}
@Test
@@ -183,7 +165,7 @@ public int[] getRequiredTokens() {
final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
check.setClassLoader(classLoader);
- Assert.assertEquals("Invalid classloader", classLoader, check.getClassLoader());
+ assertEquals("Invalid classloader", classLoader, check.getClassLoader());
}
@Test
@@ -208,11 +190,11 @@ public int[] getRequiredTokens() {
}
};
- Assert.assertArrayEquals("Invalid default tokens",
+ assertArrayEquals("Invalid default tokens",
defaultTokens, check.getDefaultTokens());
- Assert.assertArrayEquals("Invalid acceptable tokens",
+ assertArrayEquals("Invalid acceptable tokens",
defaultTokens, check.getAcceptableTokens());
- Assert.assertArrayEquals("Invalid required tokens",
+ assertArrayEquals("Invalid required tokens",
requiredTokens, check.getRequiredTokens());
}
@@ -221,9 +203,9 @@ public void testClearMessages() {
final AbstractCheck check = new DummyAbstractCheck();
check.log(1, "key", "args");
- Assert.assertEquals("Invalid message size", 1, check.getMessages().size());
+ assertEquals("Invalid message size", 1, check.getMessages().size());
check.clearMessages();
- Assert.assertEquals("Invalid message size", 0, check.getMessages().size());
+ assertEquals("Invalid message size", 0, check.getMessages().size());
}
private static final class DummyAbstractCheck extends AbstractCheck {
@@ -254,4 +236,29 @@ protected Map getCustomMessages() {
}
+ private static final class VisitCounterCheck extends AbstractCheck {
+
+ private int count;
+
+ @Override
+ public int[] getDefaultTokens() {
+ return CommonUtil.EMPTY_INT_ARRAY;
+ }
+
+ @Override
+ public int[] getAcceptableTokens() {
+ return CommonUtil.EMPTY_INT_ARRAY;
+ }
+
+ @Override
+ public int[] getRequiredTokens() {
+ return CommonUtil.EMPTY_INT_ARRAY;
+ }
+
+ @Override
+ public void visitToken(DetailAST ast) {
+ count++;
+ }
+ }
+
}
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 632e8241fe8a..4d80c71a2192 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/LocalizedMessageTest.java
@@ -23,18 +23,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-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.Map;
import java.util.ResourceBundle;
@@ -82,60 +72,6 @@ public void testBundleReloadUrlNull() throws IOException {
assertNull("Bundle should be null when reload is true and URL is null", bundle);
}
- @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);
- }
-
@Test
public void testMessageInFrench() {
final LocalizedMessage localizedMessage = createSampleLocalizedMessage();
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 061c3393d9ea..31c44a5d77f7 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
@@ -21,18 +21,11 @@
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 static org.powermock.api.mockito.PowerMockito.mock;
-import static org.powermock.api.mockito.PowerMockito.when;
import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -201,33 +194,4 @@ public void testWrongFile() throws Exception {
getCheckMessage(MSG_KEY_UNABLE_OPEN, ""), iterator.next().getMessage());
}
- @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/checks/SuppressWarningsHolderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
index 8107b5b64a05..b9911dc2ec6c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
@@ -21,45 +21,30 @@
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 static org.powermock.api.mockito.PowerMockito.mock;
import java.io.File;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
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.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;
import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(SuppressWarningsHolder.class)
public class SuppressWarningsHolderTest extends AbstractModuleTestSupport {
@Override
@@ -166,82 +151,6 @@ public void testSetAliasListWrong() {
}
}
- @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));
- }
-
@Test
public void testAnnotationInTry() throws Exception {
final Configuration checkConfig = createModuleConfig(SuppressWarningsHolder.class);
@@ -393,36 +302,4 @@ public void testClearState() throws Exception {
entries -> ((ThreadLocal>) entries).get().isEmpty()));
}
- 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