From 99c9f0df60f7df2dd50c5162b92f4c1be110a22a Mon Sep 17 00:00:00 2001 From: pbludov Date: Sun, 14 Nov 2021 18:25:11 +0300 Subject: [PATCH] Issue #10932: remove dependency on Powermock from tests --- .ci/pitest.sh | 36 +-- config/import-control-test.xml | 13 - config/intellij-idea-inspections.xml | 10 +- config/suppressions.xml | 5 +- pom.xml | 40 +-- .../tools/checkstyle/TreeWalker.java | 8 +- .../tools/checkstyle/utils/CommonUtil.java | 13 +- .../AuditEventDefaultFormatterTest.java | 37 +++ .../checkstyle/ConfigurationLoaderTest.java | 29 ++ .../tools/checkstyle/DefaultLoggerTest.java | 46 ++++ .../checkstyle/PackageObjectFactoryTest.java | 52 ++++ .../checkstyle/PropertyCacheFileTest.java | 154 +++++++++++ .../tools/checkstyle/TreeWalkerTest.java | 45 ++++ .../checks/coding/MatchXpathCheckTest.java | 2 +- .../checks/header/HeaderCheckTest.java | 200 ++++++++------ .../imports/CustomImportOrderCheckTest.java | 3 +- .../imports/ImportControlLoaderTest.java | 33 +++ .../javadoc/JavadocPackageCheckTest.java | 23 ++ .../regexp/RegexpOnFilenameCheckTest.java | 21 ++ .../internal/CliOptionsXdocsSyncTest.java | 10 +- .../AuditEventDefaultFormatterPowerTest.java | 72 ----- .../powermock/CommonUtilPowerTest.java | 66 ----- .../ConfigurationLoaderPowerTest.java | 82 ------ .../powermock/DefaultLoggerPowerTest.java | 79 ------ .../powermock/HeaderCheckPowerTest.java | 71 ----- .../ImportControlLoaderPowerTest.java | 68 ----- .../JavadocPackageCheckPowerTest.java | 62 ----- .../PackageObjectFactoryPowerTest.java | 86 ------ .../powermock/PropertyCacheFilePowerTest.java | 247 ------------------ .../RegexpOnFilenameCheckPowerTest.java | 60 ----- .../powermock/TreeWalkerPowerTest.java | 105 -------- .../meta/MetadataGeneratorUtilTest.java | 8 +- .../checkstyle/utils/CommonUtilTest.java | 116 ++++---- ...stomImportOrderEclipseDefaultPositive.java | 2 +- ...putImportOrder_EclipseDefaultNegative.java | 2 +- ...putImportOrder_EclipseDefaultPositive.java | 2 +- .../extensions/configuration.properties | 1 - 37 files changed, 669 insertions(+), 1240 deletions(-) delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/AuditEventDefaultFormatterPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/CommonUtilPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ConfigurationLoaderPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/DefaultLoggerPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ImportControlLoaderPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/JavadocPackageCheckPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageObjectFactoryPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PropertyCacheFilePowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/RegexpOnFilenameCheckPowerTest.java delete mode 100644 src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/TreeWalkerPowerTest.java delete mode 100644 src/test/resources/org/powermock/extensions/configuration.properties diff --git a/.ci/pitest.sh b/.ci/pitest.sh index 948a9ed1517..f3e64cadb7c 100755 --- a/.ci/pitest.sh +++ b/.ci/pitest.sh @@ -41,6 +41,8 @@ pitest-annotation|pitest-design \ |pitest-coding \ |pitest-regexp \ |pitest-meta \ +|pitest-tree-walker \ +|pitest-utils \ |pitest-java-ast-visitor) mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=(); @@ -59,8 +61,6 @@ pitest-main) pitest-header) mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( - "AbstractHeaderCheck.java.html:
            catch (final IOException ex) {
" - "AbstractHeaderCheck.java.html:
                throw new IllegalArgumentException("unable to load header", ex);
" "RegexpHeaderCheck.java.html:
                    isMatch = headerLineNo == headerSize
" "RegexpHeaderCheck.java.html:
                            || isMatch(line, headerLineNo);
" ); @@ -81,27 +81,15 @@ pitest-common) mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "AuditEventDefaultFormatter.java.html:
        if (lastDotIndex == -1) {
" - "AuditEventDefaultFormatter.java.html:
                checkShortName = checkFullName.substring(0, checkFullName.lastIndexOf(SUFFIX));
" - "AuditEventDefaultFormatter.java.html:
                checkShortName = checkFullName;
" - "AuditEventDefaultFormatter.java.html:
            if (checkFullName.endsWith(SUFFIX)) {
" "Checker.java.html:
                if (cacheFile != null && cacheFile.isInCache(fileName, timestamp)
" "DefaultLogger.java.html:
        closeError = errorStreamOptions == OutputStreamOptions.CLOSE;
" "DefaultLogger.java.html:
        closeInfo = infoStreamOptions == OutputStreamOptions.CLOSE;
" "DefaultLogger.java.html:
        if (closeError) {
" "DefaultLogger.java.html:
        if (closeInfo) {
" "DefaultLogger.java.html:
        if (severityLevel != SeverityLevel.IGNORE) {
" - "ConfigurationLoader.java.html:
                    catch (final CheckstyleException ex) {
" - "ConfigurationLoader.java.html:
                                        + recentModule.getName(), ex);
" - "ConfigurationLoader.java.html:
                        throw new SAXException(
" "PackageObjectFactory.java.html:
        if (instance == null
" "PackageObjectFactory.java.html:
        if (!name.contains(PACKAGE_SEPARATOR)) {
" "PackageObjectFactory.java.html:
                if (thirdPartyNameToFullModuleNames == null) {
" - "PackageObjectFactory.java.html:
            returnValue = Collections.emptyMap();
" - "PackageObjectFactory.java.html:
        catch (IOException ignore) {
" - "PropertyCacheFile.java.html:
                if (!cachedHashSum.equals(contentHashSum)) {
" - "PropertyCacheFile.java.html:
                    changed = true;
" - "PropertyCacheFile.java.html:
        catch (final IOException | NoSuchAlgorithmException ex) {
" - "PropertyCacheFile.java.html:
            throw new IllegalStateException("Unable to calculate hashcode.", ex);
" ); checkPitestReport "${ignoredItems[@]}" ;; @@ -111,7 +99,6 @@ pitest-ant) mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" - "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" "CheckstyleAntTask.java.html:
            log("To process the files took " + (processingEndTime - processingStartTime)
" "CheckstyleAntTask.java.html:
            log("Total execution took " + (endTime - startTime) + TIME_SUFFIX,
" "CheckstyleAntTask.java.html:
        log("To locate the files took " + (endTime - startTime) + TIME_SUFFIX,
" @@ -159,25 +146,6 @@ pitest-javadoc) checkPitestReport "${ignoredItems[@]}" ;; -pitest-tree-walker) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "TreeWalker.java.html:
            if (!commentChecks.isEmpty()) {
" - "TreeWalker.java.html:
            if (!ordinaryChecks.isEmpty()) {
" - "TreeWalker.java.html:
            if (filters.isEmpty()) {
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-utils) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "CommonUtil.java.html:
                catch (final URISyntaxException ex) {
" - "CommonUtil.java.html:
                    throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, ex);
" - ); - 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/import-control-test.xml b/config/import-control-test.xml index 7175d138cb8..5e9ec821e46 100644 --- a/config/import-control-test.xml +++ b/config/import-control-test.xml @@ -11,17 +11,9 @@ |org\.checkstyle.*)" regex="true"> - - - - - - - @@ -35,11 +27,6 @@ - - - - - diff --git a/config/intellij-idea-inspections.xml b/config/intellij-idea-inspections.xml index de97b29b6a3..341b24aad34 100644 --- a/config/intellij-idea-inspections.xml +++ b/config/intellij-idea-inspections.xml @@ -4592,15 +4592,10 @@ enabled_by_default="true"/> - - - @@ -270,6 +267,8 @@ files="[\\/]src[\\/]test[\\/]java[\\/]com[\\/]puppycrawl[\\/]tools[\\/]checkstyle[\\/]checks[\\/]coding[\\/]IllegalTypeCheckTest.java"/> + 3.15.0 6.41.0 0.8.7 - 2.0.9 + 4.0.0 10.6 3.1.2 1.40.0 @@ -289,13 +289,6 @@ 1.5.0 test - - - org.junit.vintage - junit-vintage-engine - ${junit.version} - test - com.google.truth truth @@ -316,23 +309,9 @@ test - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - - - - org.javassist - javassist - 3.28.0-GA - test - - - - org.powermock - powermock-module-junit4 - ${powermock.version} + org.mockito + mockito-inline + ${mockito.version} test @@ -1899,17 +1878,6 @@ - - - java16 - - [16,) - - - --illegal-access=warn - - - diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java b/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java index 2b1691160e2..0a67669559d 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java @@ -177,7 +177,7 @@ protected void processFiltered(File file, FileText fileText) throws CheckstyleEx * @param rootAST root AST element {@link DetailAST} of the file * @return filtered set of violations */ - private SortedSet getFilteredViolations( + /* package */ SortedSet getFilteredViolations( String fileName, FileContents fileContents, DetailAST rootAST) { final SortedSet result = new TreeSet<>(violations); for (Violation element : violations) { @@ -267,7 +267,7 @@ else if (TokenUtil.isCommentType(tokenId)) { * @param contents the contents of the file the AST was generated from. * @param astState state of AST. */ - private void walk(DetailAST ast, FileContents contents, + /* package */ void walk(DetailAST ast, FileContents contents, AstState astState) { notifyBegin(ast, contents, astState); processIter(ast, astState); @@ -431,8 +431,10 @@ private static SortedSet createNewCheckSortedSet() { /** * State of AST. * Indicates whether tree contains certain nodes. + * + * @noinspection PackageVisibleInnerClass */ - private enum AstState { + /* package */ enum AstState { /** * Ordinary tree. diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java index 076fa6e1d55..6cabafae10c 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java @@ -447,7 +447,7 @@ private static URI getFilepathOrClasspathUri(String filename) throws CheckstyleE public static URI getResourceFromClassPath(String filename) throws CheckstyleException { final URL configUrl; if (filename.charAt(0) == '/') { - configUrl = CommonUtil.class.getResource(filename); + configUrl = getCheckstyleResource(filename); } else { configUrl = ClassLoader.getSystemResource(filename); @@ -468,6 +468,17 @@ public static URI getResourceFromClassPath(String filename) throws CheckstyleExc return uri; } + /** + * Finds a resource with a given name in the Checkstyle resource bundle. + * This method is intended only for internal use in Checkstyle and tests. + * + * @param name name of the desired resource + * @return URI of the resource + */ + /* package */ static URL getCheckstyleResource(String name) { + return CommonUtil.class.getResource(name); + } + /** * Puts part of line, which matches regexp into given template * on positions $n where 'n' is number of matched part in line. diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java index ac6e1a0d97f..94657fbcb54 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatterTest.java @@ -19,7 +19,10 @@ package com.puppycrawl.tools.checkstyle; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; @@ -80,6 +83,40 @@ public void testCalculateBufferLength() throws Exception { assertEquals(54, result, "Buffer length is not expected"); } + @Test + public void testFormatModuleNameContainsCheckSuffix() { + final AuditEvent mock = 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]"; + assertWithMessage("Invalid format") + .that(formatter.format(mock)) + .isEqualTo(expected); + } + + @Test + public void testFormatModuleNameDoesNotContainCheckSuffix() { + final AuditEvent mock = 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]"; + assertWithMessage("Invalid format") + .that(formatter.format(mock)) + .isEqualTo(expected); + } + private static class TestModuleCheck { // no code diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java index 3ca13eec930..56473481e08 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java @@ -24,6 +24,8 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; import java.io.File; import java.lang.reflect.Constructor; @@ -36,6 +38,7 @@ import java.util.Properties; import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -618,4 +621,30 @@ public void testConstructors() throws Exception { assertEquals(1, length, "Unexpected children size"); } + @Test + public void testConfigWithIgnoreExceptionalAttributes() throws Exception { + try (MockedConstruction mocked = mockConstruction( + DefaultConfiguration.class, (mock, context) -> { + when(mock.getPropertyNames()).thenReturn(new String[] {"severity"}); + when(mock.getName()).thenReturn("MemberName"); + when(mock.getProperty("severity")).thenThrow(CheckstyleException.class); + })) { + try { + ConfigurationLoader.loadConfiguration( + getPath("InputConfigurationLoaderModuleIgnoreSeverity.xml"), + new PropertiesExpander(new Properties()), IgnoredModulesOptions.OMIT); + fail("Exception is expected"); + } + catch (CheckstyleException ex) { + final String expectedMessage = + "Problem during accessing 'severity' attribute for MemberName"; + assertWithMessage("Invalid exception cause message") + .that(ex) + .hasCauseThat() + .hasMessageThat() + .isEqualTo(expectedMessage); + } + } + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java index ccf1a7a5dd5..9140dd197a2 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java @@ -24,6 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.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; @@ -44,6 +47,7 @@ import com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions; import com.puppycrawl.tools.checkstyle.api.Violation; import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; +import com.puppycrawl.tools.checkstyle.utils.CommonUtil; public class DefaultLoggerTest { @@ -310,4 +314,46 @@ private static Method getAuditFinishMessage() throws Exception { private static Class getDefaultLoggerClass() throws Exception { return Class.forName("com.puppycrawl.tools.checkstyle.DefaultLogger"); } + + @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 Violation addExceptionMessage = new Violation(1, + Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.ADD_EXCEPTION_MESSAGE, + new String[] {"myfile"}, null, + getClass(), null); + final Violation startMessage = new Violation(1, + Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.AUDIT_STARTED_MESSAGE, + CommonUtil.EMPTY_STRING_ARRAY, null, + getClass(), null); + final Violation finishMessage = new Violation(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(); + assertWithMessage("Expected startMessage") + .that(infoOutput) + .contains(startMessage.getViolation()); + assertWithMessage("Expected finishMessage") + .that(infoOutput) + .contains(finishMessage.getViolation()); + assertWithMessage("Expected addExceptionMessage") + .that(output) + .contains(addExceptionMessage.getViolation()); + assertWithMessage("Expected IllegalStateException") + .that(output) + .contains("java.lang.IllegalStateException: upsss"); + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java index fb88473a628..7d9424740be 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/PackageObjectFactoryTest.java @@ -19,6 +19,7 @@ package com.puppycrawl.tools.checkstyle; +import static com.google.common.truth.Truth.assertWithMessage; import static com.puppycrawl.tools.checkstyle.PackageObjectFactory.AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE; import static com.puppycrawl.tools.checkstyle.PackageObjectFactory.BASE_PACKAGE; import static com.puppycrawl.tools.checkstyle.PackageObjectFactory.CHECK_SUFFIX; @@ -31,8 +32,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mockStatic; import java.io.File; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; @@ -45,6 +48,8 @@ import java.util.Set; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; @@ -52,6 +57,8 @@ import com.puppycrawl.tools.checkstyle.api.Violation; import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck; import com.puppycrawl.tools.checkstyle.internal.utils.CheckUtil; +import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; +import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil; /** * Enter a description of class PackageObjectFactoryTest.java. @@ -393,6 +400,51 @@ public void testGetShortFromFullModuleNamesThirdParty() { "Invalid simple check name"); } + /** + * 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 TestUtil} 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 Mockito#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); + + try (MockedStatic utilities = + mockStatic(ModuleReflectionUtil.class)) { + utilities.when(() -> ModuleReflectionUtil.getCheckstyleModules(packages, classLoader)) + .thenThrow(new IOException("mock exception")); + + final String internalFieldName = "thirdPartyNameToFullModuleNames"; + final Map nullMap = TestUtil.getInternalState(objectFactory, + internalFieldName); + assertWithMessage("Expected uninitialized field") + .that(nullMap) + .isNull(); + + final Object instance = objectFactory.createModule(name); + assertWithMessage("Expected empty string") + .that(instance) + .isEqualTo(""); + + final Map emptyMap = TestUtil.getInternalState(objectFactory, + internalFieldName); + assertWithMessage("Expected empty map") + .that(emptyMap) + .isEmpty(); + } + } + private static final class FailConstructorFileSet extends AbstractFileSetCheck { private FailConstructorFileSet() { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java index 04c1f7407cd..e82ed03e8a0 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java @@ -19,12 +19,15 @@ package com.puppycrawl.tools.checkstyle; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockStatic; import java.io.BufferedInputStream; import java.io.BufferedReader; @@ -32,21 +35,31 @@ import java.io.File; import java.io.IOException; import java.io.ObjectOutputStream; +import java.lang.reflect.InvocationTargetException; 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.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.MockedStatic; import com.google.common.io.BaseEncoding; import com.google.common.io.ByteStreams; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; import com.puppycrawl.tools.checkstyle.utils.CommonUtil; public class PropertyCacheFileTest extends AbstractPathTestSupport { @@ -284,4 +297,145 @@ public void testChangeInConfig() throws Exception { assertEquals(1, detailsAfterChangeInConfig.size(), "Invalid cache size"); } + @Test + public void testNonExistentResource() throws IOException { + final Configuration config = new DefaultConfiguration("myName"); + final String filePath = File.createTempFile("junit", null, temporaryFolder).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); + assertWithMessage("Config hash key should not be null") + .that(hash) + .isNotNull(); + + try (MockedStatic byteStream = mockStatic(ByteStreams.class)) { + byteStream.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); + + assertWithMessage("Should return false in file is not in cache") + .that(cache.isInCache(myFile, 1)) + .isFalse(); + + assertWithMessage("Should return false in file is not in cache") + .that(cache.isInCache(resource, 1)) + .isFalse(); + } + } + + @Test + public void testExceptionNoSuchAlgorithmException() throws Exception { + final Configuration config = new DefaultConfiguration("myName"); + final String filePath = File.createTempFile("junit", null, temporaryFolder).getPath(); + final PropertyCacheFile cache = new PropertyCacheFile(config, filePath); + cache.put("myFile", 1); + + try (MockedStatic messageDigest = mockStatic(MessageDigest.class)) { + messageDigest.when(() -> MessageDigest.getInstance("SHA-1")) + .thenThrow(NoSuchAlgorithmException.class); + try { + TestUtil.invokeStaticMethod( + PropertyCacheFile.class, "getHashCodeBasedOnObjectContent", config); + fail("InvocationTargetException is expected"); + } + catch (InvocationTargetException ex) { + assertWithMessage("Invalid exception cause") + .that(ex) + .hasCauseThat() + .hasCauseThat() + .isInstanceOf(NoSuchAlgorithmException.class); + assertWithMessage("Invalid exception message") + .that(ex) + .hasCauseThat() + .hasMessageThat() + .isEqualTo("Unable to calculate hashcode."); + } + } + } + + /** + * This test invokes {@code putExternalResources} twice to invalidate cache. + * And asserts that two different exceptions produces different content. + * + * @param messages the messages for mock exceptions + */ + @ParameterizedTest(name = "{index} - {0}") + @MethodSource("parametersForPutNonExistentExternalResource") + public void testPutNonExistentExternalResource(List messages) throws Exception { + final File cacheFile = File.createTempFile("junit", null, temporaryFolder); + + // We mock getUriByFilename method of CommonUtil to guarantee that it will + // throw CheckstyleException with the specific content. + try (MockedStatic commonUtil = mockStatic(CommonUtil.class)) { + final int numberOfRuns = messages.size(); + final String[] configHashes = new String[numberOfRuns]; + final String[] externalResourceHashes = new String[numberOfRuns]; + for (int i = 0; i < numberOfRuns; i++) { + commonUtil.when(() -> CommonUtil.getUriByFilename(any(String.class))) + .thenThrow(new CheckstyleException(messages.get(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); + assertWithMessage("Config hash key should not be null") + .that(configHashes[i]) + .isNotNull(); + + 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); + assertWithMessage("External resource hashes should not be null") + .that(externalResourceHashes[i]) + .isNotNull(); + + cache.persist(); + + final Properties cacheDetails = new Properties(); + try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) { + cacheDetails.load(reader); + } + + final int expectedNumberOfObjectsInCacheFile = 2; + assertWithMessage("Unexpected number of objects in cache") + .that(cacheDetails) + .hasSize(expectedNumberOfObjectsInCacheFile); + } + + assertWithMessage("Invalid config hash") + .that(configHashes[0]) + .isEqualTo(configHashes[1]); + final boolean isSameMessage = messages.get(0).equals(messages.get(1)); + assertWithMessage("Invalid external resource hashes") + .that(externalResourceHashes[0].equals(externalResourceHashes[1])) + .isEqualTo(isSameMessage); + } + } + + /** + * Provides parameters for {@link #testPutNonExistentExternalResource(List)} test. + * + * @return the stream of parameters + */ + private static Stream> parametersForPutNonExistentExternalResource() { + return Stream.of( + Arrays.asList("Same", "Same"), + Arrays.asList("First", "Second") + ); + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java index 6394e70d54b..141cbfd21ce 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java @@ -23,6 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import java.io.File; import java.io.Writer; @@ -39,12 +42,14 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; import org.mockito.internal.util.Checks; 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; @@ -528,6 +533,46 @@ public void testExternalResourceFiltersWithNoExternalResource() throws Exception verify(checkerConfig, filePath, expected); } + @Test + public void testBehaviourWithOnlyOrdinaryChecks() throws Exception { + final TreeWalker treeWalkerSpy = spy(new TreeWalker()); + 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 = File.createTempFile("file", ".java", temporaryFolder); + final List lines = new ArrayList<>(); + lines.add("class Test {}"); + final FileText fileText = new FileText(file, lines); + treeWalkerSpy.setFileContents(new FileContents(fileText)); + TestUtil.invokeMethod(treeWalkerSpy, "processFiltered", file, fileText); + Mockito.verify(treeWalkerSpy, times(1)).walk( + any(DetailAST.class), any(FileContents.class), any(TreeWalker.AstState.class)); + Mockito.verify(treeWalkerSpy, times(0)).getFilteredViolations( + any(String.class), any(FileContents.class), any(DetailAST.class)); + } + + @Test + public void testBehaviourWithOnlyCommentChecks() throws Exception { + final TreeWalker treeWalkerSpy = spy(new TreeWalker()); + 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 = File.createTempFile("file", ".java", temporaryFolder); + final List lines = new ArrayList<>(); + lines.add("class Test {}"); + final FileText fileText = new FileText(file, lines); + treeWalkerSpy.setFileContents(new FileContents(fileText)); + TestUtil.invokeMethod(treeWalkerSpy, "processFiltered", file, fileText); + Mockito.verify(treeWalkerSpy, times(1)).walk( + any(DetailAST.class), any(FileContents.class), any(TreeWalker.AstState.class)); + Mockito.verify(treeWalkerSpy, times(0)).getFilteredViolations( + any(String.class), any(FileContents.class), any(DetailAST.class)); + } + public static class BadJavaDocCheck extends AbstractCheck { @Override diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java index 219c253edc0..3fc9aec11b7 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java @@ -20,7 +20,7 @@ package com.puppycrawl.tools.checkstyle.checks.coding; import static com.google.common.truth.Truth.assertWithMessage; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Test; 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 9e0cbc5cbf6..57f56cb43eb 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 @@ -23,16 +23,20 @@ import static com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck.MSG_MISMATCH; import static com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck.MSG_MISSING; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; import java.io.File; +import java.io.IOException; +import java.io.LineNumberReader; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.util.Set; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedConstruction; import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -84,22 +88,22 @@ public void testWhitespaceHeader() throws Exception { public void testNonExistentHeaderFile() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); checkConfig.addProperty("headerFile", getPath("nonExistent.file")); - try { - createChecker(checkConfig); - fail("CheckstyleException is expected"); - } - catch (CheckstyleException ex) { - final String messageStart = "cannot initialize module" - + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" - + " - illegal value "; - final String causeMessageStart = "Unable to find: "; - - assertTrue(ex.getMessage().startsWith(messageStart), - "Invalid exception message, should start with: " + messageStart); - assertTrue( - ex.getCause().getCause().getCause().getMessage().startsWith(causeMessageStart), - "Invalid exception message, should start with: " + causeMessageStart); - } + final CheckstyleException ex = assertThrows(CheckstyleException.class, + () -> createChecker(checkConfig), + "CheckstyleException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .startsWith("cannot initialize module" + + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" + + " - illegal value "); + assertWithMessage("Invalid cause exception message") + .that(ex) + .hasCauseThat() + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .startsWith("Unable to find: "); } @Test @@ -107,53 +111,60 @@ public void testInvalidCharset() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); checkConfig.addProperty("headerFile", getPath("InputHeaderjava.header")); checkConfig.addProperty("charset", "XSO-8859-1"); - try { - createChecker(checkConfig); - fail("CheckstyleException is expected"); - } - catch (CheckstyleException ex) { - assertEquals("cannot initialize module" - + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" - + " - Cannot set property 'charset' to 'XSO-8859-1'", - ex.getMessage(), "Invalid exception message"); - assertEquals("unsupported charset: 'XSO-8859-1'", - ex.getCause().getCause().getCause().getMessage(), "Invalid exception message"); - } + final CheckstyleException ex = assertThrows(CheckstyleException.class, + () -> createChecker(checkConfig), + "CheckstyleException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("cannot initialize module" + + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" + + " - Cannot set property 'charset' to 'XSO-8859-1'"); + assertWithMessage("Invalid cause exception message") + .that(ex) + .hasCauseThat() + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .startsWith("unsupported charset: 'XSO-8859-1'"); } @Test - public void testEmptyFilename() throws Exception { + public void testEmptyFilename() { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); checkConfig.addProperty("headerFile", ""); - try { - createChecker(checkConfig); - fail("Checker creation should not succeed with invalid headerFile"); - } - catch (CheckstyleException ex) { - assertEquals("cannot initialize module" - + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" - + " - Cannot set property 'headerFile' to ''", - ex.getMessage(), "Invalid exception message"); - assertEquals("property 'headerFile' is missing or invalid in module" - + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck", - ex.getCause().getCause().getCause().getMessage(), "Invalid exception message"); - } + final CheckstyleException ex = assertThrows(CheckstyleException.class, + () -> createChecker(checkConfig), + "CheckstyleException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("cannot initialize module" + + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" + + " - Cannot set property 'headerFile' to ''"); + assertWithMessage("Invalid cause exception message") + .that(ex) + .hasCauseThat() + .hasCauseThat() + .hasCauseThat() + .hasMessageThat() + .isEqualTo("property 'headerFile' is missing or invalid in module" + + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck"); } @Test - public void testNullFilename() throws Exception { + public void testNullFilename() { final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class); checkConfig.addProperty("headerFile", null); - try { - createChecker(checkConfig); - fail("Checker creation should not succeed with null headerFile"); - } - catch (CheckstyleException ex) { - assertEquals("cannot initialize module" - + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" - + " - Cannot set property 'headerFile' to 'null'", - ex.getMessage(), "Invalid exception message"); - } + final CheckstyleException ex = assertThrows(CheckstyleException.class, + () -> createChecker(checkConfig), + "CheckstyleException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("cannot initialize module" + + " com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck" + + " - Cannot set property 'headerFile' to 'null'"); } @Test @@ -181,15 +192,14 @@ public void testIgnore() throws Exception { public void testSetHeaderTwice() { final HeaderCheck check = new HeaderCheck(); check.setHeader("Header"); - try { - check.setHeader("Header2"); - fail("ConversionException is expected"); - } - catch (IllegalArgumentException ex) { - assertEquals("header has already been set - " - + "set either header or headerFile, not both", ex.getMessage(), - "Invalid exception message"); - } + final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> check.setHeader("Header2"), + "IllegalArgumentException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("header has already been set - " + + "set either header or headerFile, not both"); } @Test @@ -197,17 +207,14 @@ public void testIoExceptionWhenLoadingHeaderFile() throws Exception { final HeaderCheck check = new HeaderCheck(); check.setHeaderFile(new URI("test://bad")); - try { - TestUtil.invokeMethod(check, "loadHeaderFile"); - fail("InvocationTargetException expected"); - } - catch (InvocationTargetException ex) { - assertWithMessage("Invalid exception cause message") - .that(ex) - .hasCauseThat() - .hasMessageThat() - .startsWith("unable to load header file "); - } + final InvocationTargetException ex = assertThrows(InvocationTargetException.class, + () -> TestUtil.invokeMethod(check, "loadHeaderFile"), + "InvocationTargetException expected"); + assertWithMessage("Invalid exception cause message") + .that(ex) + .hasCauseThat() + .hasMessageThat() + .startsWith("unable to load header file "); } @Test @@ -254,21 +261,18 @@ public void testIgnoreLinesSorted() throws Exception { } @Test - public void testLoadHeaderFileTwice() throws Exception { + public void testLoadHeaderFileTwice() { final HeaderCheck check = new HeaderCheck(); check.setHeader("Header"); - try { - TestUtil.invokeMethod(check, "loadHeaderFile"); - fail("InvocationTargetException is expected"); - } - catch (InvocationTargetException ex) { - assertWithMessage("Invalid exception cause message") + final InvocationTargetException ex = assertThrows(InvocationTargetException.class, + () -> TestUtil.invokeMethod(check, "loadHeaderFile"), + "InvocationTargetException expected"); + assertWithMessage("Invalid exception cause message") .that(ex) - .hasCauseThat() + .hasCauseThat() .hasMessageThat() - .isEqualTo("header has already been set - " - + "set either header or headerFile, not both"); - } + .isEqualTo("header has already been set - " + + "set either header or headerFile, not both"); } @Test @@ -294,4 +298,28 @@ public void testExternalResource() throws Exception { assertEquals(1, results.size(), "Invalid result size"); assertEquals(uri.toString(), results.iterator().next(), "Invalid resource location"); } + + @Test + public void testIoExceptionWhenLoadingHeader() { + final HeaderCheck check = new HeaderCheck(); + final Exception ex = assertThrows(IllegalArgumentException.class, + () -> { + try (MockedConstruction mocked = mockConstruction( + LineNumberReader.class, (mock, context) -> { + when(mock.readLine()).thenThrow(IOException.class); + })) { + check.setHeader("header"); + } + }, + "IllegalArgumentException expected"); + assertWithMessage("Invalid exception cause") + .that(ex) + .hasCauseThat() + .isInstanceOf(IOException.class); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("unable to load header"); + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java index 2de87b0d33a..405318d4df5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java @@ -730,8 +730,7 @@ public void testInputCustomImportOrderEclipseDefaultPositive() throws Exception "26:1: " + getCheckMessage(MSG_NONGROUP_EXPECTED, SPECIAL, "javax.swing.JComponent"), "27:1: " + getCheckMessage(MSG_NONGROUP_EXPECTED, SPECIAL, "javax.swing.JTable"), "29:1: " + getCheckMessage(MSG_NONGROUP_EXPECTED, THIRD, "org.junit.Test"), - "30:1: " + getCheckMessage(MSG_NONGROUP_EXPECTED, THIRD, - "org.powermock.api.mockito.PowerMockito"), + "30:1: " + getCheckMessage(MSG_NONGROUP_EXPECTED, THIRD, "org.mockito.Mock"), "34:1: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "sun.tools.java.ArrayType"), }; verifyWithInlineConfigParser( diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.java index 18dc98b04c3..8a38a9a9111 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoaderTest.java @@ -19,22 +19,30 @@ package com.puppycrawl.tools.checkstyle.checks.imports; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URI; +import java.net.URL; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; import org.xml.sax.helpers.AttributesImpl; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; @@ -124,4 +132,29 @@ public void testLoadThrowsException() throws Exception { } } + @Test + public void testInputStreamFailsOnRead() throws Exception { + try (InputStream inputStream = mock(InputStream.class)) { + final int available = Mockito.doThrow(IOException.class).when(inputStream).available(); + + final URL url = mock(URL.class); + when(url.openStream()).thenReturn(inputStream); + + final URI uri = mock(URI.class); + when(uri.toURL()).thenReturn(url); + + try { + ImportControlLoader.load(uri); + // Using available to bypass 'ignored result' warning + fail("exception expected " + available); + } + catch (CheckstyleException ex) { + assertWithMessage("Invalid exception class") + .that(ex) + .hasCauseThat() + .isInstanceOf(SAXParseException.class); + } + } + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.java index 9ddc50e2ff3..c1352f599c5 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheckTest.java @@ -23,6 +23,8 @@ import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck.MSG_PACKAGE_INFO; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.io.File; import java.util.Collections; @@ -161,4 +163,25 @@ public void testNonJava() throws Exception { expected); } + /** + * Test require readable file with no parent to be used. + * Usage of Mockito.spy() is the only way to satisfy these requirements + * without the need to create new file in current working directory. + * + * @throws Exception if error occurs + */ + @Test + public void testWithFileWithoutParent() throws Exception { + final DefaultConfiguration moduleConfig = createModuleConfig(JavadocPackageCheck.class); + final File fileWithoutParent = spy( + new File(getPath("noparentfile" + File.separator + "package-info.java"))); + when(fileWithoutParent.getParent()).thenReturn(null); + when(fileWithoutParent.getParentFile()).thenReturn(null); + final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + verify(createChecker(moduleConfig), + new File[] {fileWithoutParent}, + getPath("annotation" + + File.separator + "package-info.java"), expected); + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheckTest.java index 1afe4b84c28..b9b4a4c022d 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheckTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheckTest.java @@ -23,6 +23,8 @@ import static com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck.MSG_MISMATCH; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.io.File; import java.util.Collections; @@ -254,4 +256,23 @@ public void testException() throws Exception { } } + /** + * Test require readable file with no parent to be used. + * Usage of Mockito.spy() is the only way to satisfy these requirements + * without the need to create new file in current working directory. + * + * @throws Exception if error occurs + */ + @Test + public void testWithFileWithoutParent() throws Exception { + final DefaultConfiguration moduleConfig = createModuleConfig(RegexpOnFilenameCheck.class); + final File fileWithoutParent = spy(new File(getPath("package-info.java"))); + when(fileWithoutParent.getParent()).thenReturn(null); + when(fileWithoutParent.getParentFile()).thenReturn(null); + final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + verify(createChecker(moduleConfig), + new File[] {fileWithoutParent}, + getPath("package-info.java"), expected); + } + } diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java index 01af68b204f..f322dcf9645 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java @@ -104,10 +104,12 @@ public void validateCliUsageSection() throws Exception { .filter(names -> names.length() != 2) .collect(Collectors.toSet()); - assertEquals("Short parameters in Main.java and cmdline" - + ".xml.vm should match", shortParamsXdoc, shortParamsMain); - assertEquals("Long parameters in Main.java and cmdline" - + ".xml.vm should match", longParamsXdoc, longParamsMain); + assertWithMessage("Short parameters in Main.java and cmdline.xml.vm should match") + .that(shortParamsXdoc) + .isEqualTo(shortParamsMain); + assertWithMessage("Long parameters in Main.java and cmdline.xml.vm should match") + .that(longParamsXdoc) + .isEqualTo(longParamsMain); } private static Set getParameters(String text, String regex) { diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/AuditEventDefaultFormatterPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/AuditEventDefaultFormatterPowerTest.java deleted file mode 100644 index b76e6e5c392..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/AuditEventDefaultFormatterPowerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertEquals; -import static org.mockito.Mockito.when; - -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.AuditEventDefaultFormatter; -import com.puppycrawl.tools.checkstyle.AuditEventFormatter; -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.SeverityLevel; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(AuditEvent.class) -public class AuditEventDefaultFormatterPowerTest { - - @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)); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/CommonUtilPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/CommonUtilPowerTest.java deleted file mode 100644 index 9a8f0e581bb..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/CommonUtilPowerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.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.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.net.URISyntaxException; -import java.net.URL; - -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 com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; -import com.puppycrawl.tools.checkstyle.utils.CommonUtilTest; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ CommonUtil.class, CommonUtilTest.class }) -public class CommonUtilPowerTest { - - @Test - public void testLoadSuppressionsUriSyntaxException() throws Exception { - final URL configUrl = mock(URL.class); - - when(configUrl.toURI()).thenThrow(URISyntaxException.class); - mockStatic(CommonUtil.class, Mockito.CALLS_REAL_METHODS); - final String fileName = "/suppressions_none.xml"; - when(CommonUtil.class.getResource(fileName)).thenReturn(configUrl); - - try { - CommonUtil.getUriByFilename(fileName); - fail("Exception is expected"); - } - catch (CheckstyleException ex) { - assertTrue("Invalid exception cause", ex.getCause() instanceof URISyntaxException); - assertEquals("Invalid exception message", - "Unable to find: " + fileName, ex.getMessage()); - } - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ConfigurationLoaderPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ConfigurationLoaderPowerTest.java deleted file mode 100644 index fc5e4d01f09..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ConfigurationLoaderPowerTest.java +++ /dev/null @@ -1,82 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertEquals; -import static org.junit.Assert.fail; -import static org.powermock.api.mockito.PowerMockito.when; - -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 com.puppycrawl.tools.checkstyle.AbstractPathTestSupport; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.PropertiesExpander; -import com.puppycrawl.tools.checkstyle.ThreadModeSettings; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({DefaultConfiguration.class, ConfigurationLoader.class}) -public class ConfigurationLoaderPowerTest extends AbstractPathTestSupport { - - @Override - protected String getPackageLocation() { - return "com/puppycrawl/tools/checkstyle/configurationloader"; - } - - @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.getPropertyNames()).thenReturn(new String[] {"severity"}); - when(tested.getName()).thenReturn("MemberName"); - when(tested.getProperty("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()), IgnoredModulesOptions.OMIT); - fail("Exception is expected"); - } - catch (CheckstyleException expected) { - assertEquals("Invalid exception cause message", - "Problem during accessing 'severity' attribute for MemberName", - expected.getCause().getMessage()); - } - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/DefaultLoggerPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/DefaultLoggerPowerTest.java deleted file mode 100644 index 5d8b02a0636..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/DefaultLoggerPowerTest.java +++ /dev/null @@ -1,79 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertTrue; -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; -import java.nio.charset.StandardCharsets; - -import org.junit.Test; - -import com.puppycrawl.tools.checkstyle.DefaultLogger; -import com.puppycrawl.tools.checkstyle.Definitions; -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.AutomaticBean; -import com.puppycrawl.tools.checkstyle.api.Violation; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class DefaultLoggerPowerTest { - - @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 Violation addExceptionMessage = new Violation(1, - Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.ADD_EXCEPTION_MESSAGE, - new String[] {"myfile"}, null, - getClass(), null); - final Violation startMessage = new Violation(1, - Definitions.CHECKSTYLE_BUNDLE, DefaultLogger.AUDIT_STARTED_MESSAGE, - CommonUtil.EMPTY_STRING_ARRAY, null, - getClass(), null); - final Violation finishMessage = new Violation(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("Violation should contain exception info, but was " + infoOutput, - infoOutput.contains(startMessage.getViolation())); - assertTrue("Violation should contain exception info, but was " + infoOutput, - infoOutput.contains(finishMessage.getViolation())); - assertTrue("Violation should contain exception info, but was " + output, - output.contains(addExceptionMessage.getViolation())); - assertTrue("Violation should contain exception info, but was " + output, - output.contains("java.lang.IllegalStateException: upsss")); - } - -} 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 deleted file mode 100644 index 4ec1aa6710b..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/HeaderCheckPowerTest.java +++ /dev/null @@ -1,71 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; - -import java.io.IOException; - -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.checks.header.AbstractHeaderCheck; -import com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck; -import com.puppycrawl.tools.checkstyle.checks.header.HeaderCheckTest; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ HeaderCheck.class, HeaderCheckTest.class, AbstractHeaderCheck.class }) -public class HeaderCheckPowerTest extends AbstractModuleTestSupport { - - @Override - 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()); - PowerMockito.doThrow(new IOException("expected exception")).when(check, "loadHeader", - any()); - - try { - check.setHeader("header"); - fail("Exception expected"); - } - catch (IllegalArgumentException ex) { - assertTrue("Invalid exception cause", ex.getCause() instanceof IOException); - assertEquals("Invalid exception message", "unable to load header", ex.getMessage()); - } - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ImportControlLoaderPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ImportControlLoaderPowerTest.java deleted file mode 100644 index 800cbb8cf03..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/ImportControlLoaderPowerTest.java +++ /dev/null @@ -1,68 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertSame; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.BDDMockito; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.xml.sax.SAXParseException; - -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.checks.imports.ImportControlLoader; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ImportControlLoader.class, URI.class}) -public class ImportControlLoaderPowerTest { - - @Test - public void testInputStreamFailsOnRead() throws Exception { - final InputStream inputStream = PowerMockito.mock(InputStream.class); - final int available = Mockito.doThrow(IOException.class).when(inputStream).available(); - - final URL url = PowerMockito.mock(URL.class); - BDDMockito.given(url.openStream()).willReturn(inputStream); - - final URI uri = PowerMockito.mock(URI.class); - BDDMockito.given(uri.toURL()).willReturn(url); - - try { - ImportControlLoader.load(uri); - // Using available to bypass 'ignored result' warning - fail("exception expected " + available); - } - catch (CheckstyleException ex) { - assertSame("Invalid exception class", - SAXParseException.class, ex.getCause().getClass()); - } - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/JavadocPackageCheckPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/JavadocPackageCheckPowerTest.java deleted file mode 100644 index fbfd6bfa720..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/JavadocPackageCheckPowerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.File; - -import org.junit.Test; - -import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class JavadocPackageCheckPowerTest extends AbstractModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/puppycrawl/tools/checkstyle/checks/javadoc/javadocpackage"; - } - - /** - * Test require readable file with no parent to be used. - * Usage of Mockito.spy() is the only way to satisfy these requirements - * without the need to create new file in current working directory. - * - * @throws Exception if error occurs - */ - @Test - public void testWithFileWithoutParent() throws Exception { - final DefaultConfiguration moduleConfig = createModuleConfig(JavadocPackageCheck.class); - final File fileWithoutParent = spy(new File(getPath("noparentfile" - + File.separator + "package-info.java"))); - when(fileWithoutParent.getParent()).thenReturn(null); - when(fileWithoutParent.getParentFile()).thenReturn(null); - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - verify(createChecker(moduleConfig), - new File[] {fileWithoutParent}, - getPath("annotation" - + File.separator + "package-info.java"), expected); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageObjectFactoryPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageObjectFactoryPowerTest.java deleted file mode 100644 index 1e17ba4e528..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PackageObjectFactoryPowerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.PackageObjectFactory.ModuleLoadOption.TRY_IN_ALL_REGISTERED_PACKAGES; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.powermock.api.mockito.PowerMockito.doThrow; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -import java.io.IOException; -import java.util.Collections; -import java.util.Map; -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 com.puppycrawl.tools.checkstyle.PackageObjectFactory; -import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; -import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil; - -@RunWith(PowerMockRunner.class) -@PowerMockIgnore(value = "com.puppycrawl.tools.checkstyle.api.*", globalIgnore = false) -@PrepareForTest(ModuleReflectionUtil.class) -public class PackageObjectFactoryPowerTest { - - /** - * 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 TestUtil#getInternalState} 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 = TestUtil.getInternalState(objectFactory, - internalFieldName); - assertNull("Expected uninitialized field", nullMap); - - final Object instance = objectFactory.createModule(name); - assertEquals("Expected empty string", "", instance); - - final Map emptyMap = TestUtil.getInternalState(objectFactory, - internalFieldName); - assertEquals("Expected empty map", Collections.emptyMap(), emptyMap); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PropertyCacheFilePowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PropertyCacheFilePowerTest.java deleted file mode 100644 index 36603b1438e..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/PropertyCacheFilePowerTest.java +++ /dev/null @@ -1,247 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.junit.Rule; -import org.junit.Test; -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.google.common.io.ByteStreams; -import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.PropertyCacheFile; -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}) -public class PropertyCacheFilePowerTest extends AbstractPathTestSupport { - - @Rule - public final TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Override - protected String getPackageLocation() { - return "com/puppycrawl/tools/checkstyle/propertycachefile"; - } - - /** - * 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 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(); - try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) { - cacheDetails.load(reader); - } - - 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(); - try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) { - cacheDetails.load(reader); - } - - 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]); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/RegexpOnFilenameCheckPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/RegexpOnFilenameCheckPowerTest.java deleted file mode 100644 index 58c7cf938e2..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/RegexpOnFilenameCheckPowerTest.java +++ /dev/null @@ -1,60 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.File; - -import org.junit.Test; - -import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class RegexpOnFilenameCheckPowerTest extends AbstractModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/puppycrawl/tools/checkstyle/checks/regexp/regexponfilename"; - } - - /** - * Test require readable file with no parent to be used. - * Usage of Mockito.spy() is the only way to satisfy these requirements - * without the need to create new file in current working directory. - * - * @throws Exception if error occurs - */ - @Test - public void testWithFileWithoutParent() throws Exception { - final DefaultConfiguration moduleConfig = createModuleConfig(RegexpOnFilenameCheck.class); - final File fileWithoutParent = spy(new File(getPath("package-info.java"))); - when(fileWithoutParent.getParent()).thenReturn(null); - when(fileWithoutParent.getParentFile()).thenReturn(null); - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - verify(createChecker(moduleConfig), - new File[] {fileWithoutParent}, - getPath("package-info.java"), expected); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/TreeWalkerPowerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/TreeWalkerPowerTest.java deleted file mode 100644 index 0a24cc6dad7..00000000000 --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/powermock/TreeWalkerPowerTest.java +++ /dev/null @@ -1,105 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2021 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.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.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import org.junit.Rule; -import org.junit.Test; -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.AbstractModuleTestSupport; -import com.puppycrawl.tools.checkstyle.PackageObjectFactory; -import com.puppycrawl.tools.checkstyle.TreeWalker; -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.checks.indentation.CommentsIndentationCheck; -import com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck; -import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(TreeWalker.class) -public class TreeWalkerPowerTest extends AbstractModuleTestSupport { - - @Rule - public final TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Override - protected String getPackageLocation() { - return "com/puppycrawl/tools/checkstyle/treewalker"; - } - - @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 {}"); - final FileText fileText = new FileText(file, lines); - treeWalkerSpy.setFileContents(new FileContents(fileText)); - TestUtil.invokeMethod(treeWalkerSpy, "processFiltered", file, fileText); - verifyPrivate(treeWalkerSpy, times(1)).invoke("walk", - any(DetailAST.class), any(FileContents.class), any(classAstState)); - verifyPrivate(treeWalkerSpy, times(0)).invoke("getFilteredViolations", - 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 {}"); - final FileText fileText = new FileText(file, lines); - treeWalkerSpy.setFileContents(new FileContents(fileText)); - TestUtil.invokeMethod(treeWalkerSpy, "processFiltered", file, fileText); - verifyPrivate(treeWalkerSpy, times(1)).invoke("walk", - any(DetailAST.class), any(FileContents.class), any(classAstState)); - verifyPrivate(treeWalkerSpy, times(0)).invoke("getFilteredViolations", - any(String.class), any(FileContents.class), any(DetailAST.class)); - } - -} diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtilTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtilTest.java index 1efed6f5712..b0492847842 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtilTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtilTest.java @@ -19,7 +19,7 @@ package com.puppycrawl.tools.checkstyle.meta; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertWithMessage; import java.nio.file.Files; import java.nio.file.Path; @@ -67,8 +67,10 @@ public void testMetadataFilesGenerationAllFiles() throws Exception { .sorted() .collect(Collectors.toCollection(LinkedHashSet::new)); checkstyleModules.removeAll(modulesContainingNoMetadataFile); - assertEquals("Number of generated metadata files dont match with number of checkstyle " - + "module", checkstyleModules, metaFiles); + assertWithMessage("Number of generated metadata files don't match " + + "with number of checkstyle module") + .that(checkstyleModules) + .isEqualTo(metaFiles); } /** diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilTest.java index 3d470f09aec..4b93c4e6dfd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilTest.java @@ -19,6 +19,7 @@ package com.puppycrawl.tools.checkstyle.utils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; @@ -28,15 +29,20 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Dictionary; import java.util.Properties; @@ -44,10 +50,12 @@ import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport; import com.puppycrawl.tools.checkstyle.ConfigurationLoader; import com.puppycrawl.tools.checkstyle.PropertiesExpander; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; public class CommonUtilTest extends AbstractPathTestSupport { @@ -106,26 +114,24 @@ public void testCreatePattern() { @Test public void testBadRegex() { - try { - CommonUtil.createPattern("["); - fail("exception expected"); - } - catch (IllegalArgumentException ex) { - assertEquals("Failed to initialise regular expression [", ex.getMessage(), - "Invalid exception message"); - } + final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> CommonUtil.createPattern("["), + "IllegalArgumentException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("Failed to initialise regular expression ["); } @Test public void testBadRegex2() { - try { - CommonUtil.createPattern("[", Pattern.MULTILINE); - fail("exception expected"); - } - catch (IllegalArgumentException ex) { - assertEquals("Failed to initialise regular expression [", ex.getMessage(), - "Invalid exception message"); - } + final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> CommonUtil.createPattern("[", Pattern.MULTILINE), + "IllegalArgumentException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("Failed to initialise regular expression ["); } @Test @@ -211,14 +217,13 @@ public void testGetExistingConstructor() throws NoSuchMethodException { @Test public void testGetNonExistentConstructor() { - try { - CommonUtil.getConstructor(Math.class); - fail("IllegalStateException is expected"); - } - catch (IllegalStateException expected) { - assertSame(NoSuchMethodException.class, expected.getCause().getClass(), - "Invalid exception cause"); - } + final IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> CommonUtil.getConstructor(Math.class), + "IllegalStateException expected"); + assertWithMessage("Invalid exception cause") + .that(ex) + .hasCauseThat() + .isInstanceOf(NoSuchMethodException.class); } @Test @@ -234,15 +239,13 @@ public void testInvokeConstructor() throws NoSuchMethodException { @Test public void testInvokeConstructorThatFails() throws NoSuchMethodException { final Constructor constructor = Dictionary.class.getConstructor(); - - try { - CommonUtil.invokeConstructor(constructor); - fail("IllegalStateException is expected"); - } - catch (IllegalStateException expected) { - assertSame(InstantiationException.class, - expected.getCause().getClass(), "Invalid exception cause"); - } + final IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> CommonUtil.invokeConstructor(constructor), + "IllegalStateException expected"); + assertWithMessage("Invalid exception cause") + .that(ex) + .hasCauseThat() + .isInstanceOf(InstantiationException.class); } @Test @@ -257,15 +260,17 @@ public void testClose() { @Test public void testCloseWithException() { - try { - CommonUtil.close(() -> { - throw new IOException("Test IOException"); - }); - fail("exception expected"); - } - catch (IllegalStateException ex) { - assertEquals("Cannot close the stream", ex.getMessage(), "Invalid exception message"); - } + final IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> { + CommonUtil.close(() -> { + throw new IOException("Test IOException"); + }); + }, + "IllegalStateException expected"); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("Cannot close the stream"); } @Test @@ -489,6 +494,29 @@ public void testGetUriByFilenameFindsRelativeResourceOnClasspathPrefix() throws assertEquals("Checker", config.getName(), "Unexpected config name!"); } + @Test + public void testLoadSuppressionsUriSyntaxException() throws Exception { + final URL configUrl = mock(URL.class); + when(configUrl.toURI()).thenThrow(URISyntaxException.class); + try (MockedStatic utilities = + mockStatic(CommonUtil.class, CALLS_REAL_METHODS)) { + final String fileName = "/suppressions_none.xml"; + utilities.when(() -> CommonUtil.getCheckstyleResource(fileName)).thenReturn(configUrl); + + final CheckstyleException ex = assertThrows(CheckstyleException.class, + () -> CommonUtil.getUriByFilename(fileName), + "CheckstyleException expected"); + assertWithMessage("Invalid exception cause") + .that(ex) + .hasCauseThat() + .isInstanceOf(URISyntaxException.class); + assertWithMessage("Invalid exception message") + .that(ex) + .hasMessageThat() + .isEqualTo("Unable to find: " + fileName); + } + } + private static class TestCloseable implements Closeable { private boolean closed; diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderEclipseDefaultPositive.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderEclipseDefaultPositive.java index 8b86e54ed00..853ab5fb3a2 100644 --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderEclipseDefaultPositive.java +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderEclipseDefaultPositive.java @@ -27,7 +27,7 @@ import javax.swing.JTable; // violation import org.junit.Test; // violation -import org.powermock.api.mockito.PowerMockito; // violation +import org.mockito.Mock; // violation import com.some.api.DetailClass; diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultNegative.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultNegative.java index a72eb53ffa0..8e71cf0c02f 100644 --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultNegative.java +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultNegative.java @@ -31,7 +31,7 @@ import sun.tools.java.ArrayType; // ok import org.junit.Test; // violation -import org.powermock.api.mockito.PowerMockito; // ok +import org.mockito.Mock; // ok import com.some.api.DetailClass; // ok diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultPositive.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultPositive.java index 555aca7cf47..c747b0e5dfd 100644 --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultPositive.java +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrder_EclipseDefaultPositive.java @@ -30,7 +30,7 @@ import javax.swing.JTable; // ok import org.junit.Test; // ok -import org.powermock.api.mockito.PowerMockito; // ok +import org.mockito.Mock; // ok import com.some.api.DetailClass; // ok diff --git a/src/test/resources/org/powermock/extensions/configuration.properties b/src/test/resources/org/powermock/extensions/configuration.properties deleted file mode 100644 index ce04b51fd08..00000000000 --- a/src/test/resources/org/powermock/extensions/configuration.properties +++ /dev/null @@ -1 +0,0 @@ -powermock.global-ignore=com.sun.org.apache.xerces.*,javax.xml.parsers.*,org.w3c.dom.*,org.xml.sax.*