GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [java] Improve TestClassWithoutTestCases by adangel · Pull Request #4162 · pmd/pmd

[java] Improve TestClassWithoutTestCases #4162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
adangel merged 5 commits into pmd:master from adangel:improve-TestClassWithoutTestCases
Oct 28, 2022

Uh oh!

There was an error while loading. Please reload this page.

Merged

[java] Improve TestClassWithoutTestCases #4162

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit Hold shift + click to select a range
33ede7f
[java] Improve TestClassWithoutTestCases
adangel Oct 15, 2022
0363c61
[java] TestClassWithoutTestCases - support JUnit5 nested tests
adangel Oct 20, 2022
5860f64
[java] TestClassWithoutTestCases - improve nested class support
adangel Oct 20, 2022
dd26af7
[java] TestClassWithoutTestCases - improve message
adangel Oct 20, 2022
1176488
[java] TestClassWithoutTestCases - fix default pattern
adangel Oct 21, 2022
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Next Next commit
[java] Improve TestClassWithoutTestCases
- Added new property "testClassPatterns" to property detect empty test classes
- Added support for different JUnit5 annotations (like ParameterizedTest)
- Added support for TestNG

- Fixes #929
- Fixes #2636
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@adangel
adangel committed Oct 15, 2022
commit 33ede7fbc264c0abcdf1123f29a7095167262d84

There are no files selected for viewing

10 changes: 10 additions & 0 deletions 10 docs/pages/release_notes.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,23 @@ This is a {{ site.pmd.release_type }} release.

The rule is part of the quickstart.xml ruleset.

#### Modified Rules

* The Java rule {% rule java/errorprone/TestClassWithoutTestCases %} has a new property `testClassPattern`. This is
used to detect empty test classes by name. Previously this rule could only detect empty JUnit3 test cases
properly. To switch back to the old behavior, this property can be set to an empty value which disables the
test class detection by pattern.

### Fixed Issues
* apex
* [#4149](https://github.com/pmd/pmd/issues/4149): \[apex] New rule: ApexUnitTestClassShouldHaveRunAs
* doc
* [#4144](https://github.com/pmd/pmd/pull/4144) \[doc] Update docs to reflect supported languages
* java-documentation
* [#4141](https://github.com/pmd/pmd/issues/4141): \[java] UncommentedEmptyConstructor FP when constructor annotated with @<!-- -->Autowired
* java-errorprone
* [#929](https://github.com/pmd/pmd/issues/929): \[java] Inconsistent results with TestClassWithoutTestCases
* [#2636](https://github.com/pmd/pmd/issues/2636): \[java] TestClassWithoutTestCases false positive with JUnit5 ParameterizedTest

### API Changes

Expand Down
73 changes: 62 additions & 11 deletions 73 pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/AbstractJUnitRule.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

package net.sourceforge.pmd.lang.java.rule;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.annotation.InternalApi;
Expand All @@ -30,6 +34,14 @@ public abstract class AbstractJUnitRule extends AbstractJavaRule {
protected static final String JUNIT3_CLASS_NAME = "junit.framework.TestCase";
protected static final String JUNIT4_CLASS_NAME = "org.junit.Test";
protected static final String JUNIT5_CLASS_NAME = "org.junit.jupiter.api.Test";
private static final Set<String> JUNIT5_TEST_ANNOTATIONS = new HashSet<>(Arrays.asList(
JUNIT5_CLASS_NAME,
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.api.TestFactory",
"org.junit.jupiter.api.TestTemplate",
"org.junit.jupiter.params.ParameterizedTest"));

private static final String TESTNG_ANNOTATION = "org.testng.annotations.Test";

protected boolean isJUnit3Class;
protected boolean isJUnit4Class;
Expand Down Expand Up @@ -92,12 +104,12 @@ protected void analyzeJUnitClass(ASTClassOrInterfaceDeclaration node) {

if (isJUnit4Class && isJUnit5Class) {
isJUnit4Class &= hasImports(node, JUNIT4_CLASS_NAME);
isJUnit5Class &= hasImports(node, JUNIT5_CLASS_NAME);
isJUnit5Class &= hasImports(node, JUNIT5_TEST_ANNOTATIONS);
}
}

public static boolean isTestClass(ASTClassOrInterfaceBody node) {
return !isAbstractClass(node)
return !isAbstractClass(node) && node.getParent() instanceof ASTClassOrInterfaceDeclaration
&& (isTestClassJUnit3(node) || isTestClassJUnit4(node) || isTestClassJUnit5(node));
}

Expand Down Expand Up @@ -131,7 +143,7 @@ public static boolean isTestClassJUnit5(ASTClassOrInterfaceBody node) {
Node parent = node.getParent();
if (parent instanceof TypeNode) {
TypeNode type = (TypeNode) parent;
return isJUnit5Class(type) && hasImports(type, JUNIT5_CLASS_NAME);
return isJUnit5Class(type) && hasImports(type, JUNIT5_TEST_ANNOTATIONS);
}
return false;
}
Expand All @@ -145,7 +157,8 @@ public static boolean isTestMethod(ASTMethodDeclaration method) {
ASTClassOrInterfaceBody type = method.getFirstParentOfType(ASTClassOrInterfaceBody.class);
return isTestClassJUnit3(type) && method.isPublic() && method.isVoid() && method.getName().startsWith("test")
|| isTestClassJUnit4(type) && method.isPublic() && doesNodeContainJUnitAnnotation(method.getParent(), JUNIT4_CLASS_NAME)
|| isTestClassJUnit5(type) && doesNodeContainJUnitAnnotation(method.getParent(), JUNIT5_CLASS_NAME);
|| isTestClassJUnit5(type) && doesNodeContainJUnitAnnotation(method.getParent(), JUNIT5_TEST_ANNOTATIONS)
|| doesNodeContainJUnitAnnotation(method.getParent(), TESTNG_ANNOTATION);
}

public boolean isJUnitMethod(ASTMethodDeclaration method, Object data) {
Expand All @@ -170,7 +183,7 @@ private boolean isJUnit4Method(ASTMethodDeclaration method) {
}

private boolean isJUnit5Method(ASTMethodDeclaration method) {
return isJUnit5Class && doesNodeContainJUnitAnnotation(method.getParent(), JUNIT5_CLASS_NAME);
return isJUnit5Class && doesNodeContainJUnitAnnotation(method.getParent(), JUNIT5_TEST_ANNOTATIONS);
}

private boolean isJUnit3Method(ASTMethodDeclaration method) {
Expand All @@ -186,34 +199,72 @@ private static boolean isJUnit4Class(JavaNode node) {
}

private static boolean isJUnit5Class(JavaNode node) {
return doesNodeContainJUnitAnnotation(node, JUNIT5_CLASS_NAME);
return doesNodeContainJUnitAnnotation(node, JUNIT5_TEST_ANNOTATIONS);
}

private static boolean doesNodeContainJUnitAnnotation(JavaNode node, String annotationTypeClassName) {
return doesNodeContainJUnitAnnotation(node, Collections.singleton(annotationTypeClassName));
}

private static boolean doesNodeContainJUnitAnnotation(JavaNode node, Set<String> annotationTypeClassNames) {
List<ASTAnnotation> annotations = node.findDescendantsOfType(ASTAnnotation.class);
for (ASTAnnotation annotation : annotations) {
Node annotationTypeNode = annotation.getChild(0);
TypeNode annotationType = (TypeNode) annotationTypeNode;
if (annotationType.getType() == null) {
ASTName name = annotationTypeNode.getFirstChildOfType(ASTName.class);
if (name != null && (name.hasImageEqualTo("Test") || name.hasImageEqualTo(annotationTypeClassName))) {
return true;
if (name != null) {
for (String annotationTypeName : annotationTypeClassNames) {
if (areNamesEqual(name, annotationTypeName)) {
return true;
}
}
}
} else {
for (String annotationTypeClassName : annotationTypeClassNames) {
if (TypeTestUtil.isA(annotationTypeClassName, annotationType)) {
return true;
}
}
} else if (TypeTestUtil.isA(annotationTypeClassName, annotationType)) {
return true;
}
}
return false;
}

private static boolean hasImports(JavaNode node, String className) {
return hasImports(node, Collections.singleton(className));
}

private static boolean hasImports(JavaNode node, Set<String> classNames) {
List<ASTImportDeclaration> imports = node.getRoot().findDescendantsOfType(ASTImportDeclaration.class);
for (ASTImportDeclaration importDeclaration : imports) {
ASTName name = importDeclaration.getFirstChildOfType(ASTName.class);
if (name != null && name.hasImageEqualTo(className)) {
// imports are always fully qualified
if (name != null && classNames.contains(name.getImage())) {
return true;
}
}
return false;
}

/**
* Compares the name against the given fully qualified name. If a direct comparison doesn't
* work, try to compare as a simple name.
*
* <p>Note: This method is only used, if the auxclasspath is incomplete.</p>
*/
private static boolean areNamesEqual(ASTName node, String fullyQualifiedAnnotationName) {
String simpleName = node.getImage();
if (simpleName.equals(fullyQualifiedAnnotationName)) {
return true;
}

String simpleAnnotationName = fullyQualifiedAnnotationName;
int lastDot = fullyQualifiedAnnotationName.lastIndexOf('.');
if (lastDot != -1) {
simpleAnnotationName = fullyQualifiedAnnotationName.substring(lastDot + 1);
}
// when comparing by simple name, double check whether we have a import to avoid false positives
return simpleName.equals(simpleAnnotationName) && hasImports(node, fullyQualifiedAnnotationName);
}
}
44 changes: 43 additions & 1 deletion 44 ...ain/java/net/sourceforge/pmd/lang/java/rule/errorprone/TestClassWithoutTestCasesRule.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,35 @@
package net.sourceforge.pmd.lang.java.rule.errorprone;

import java.util.List;
import java.util.regex.Pattern;

import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBody;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceBodyDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTPackageDeclaration;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.rule.AbstractJUnitRule;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;

public class TestClassWithoutTestCasesRule extends AbstractJavaRule {

private static final PropertyDescriptor<Pattern> TEST_CLASS_PATTERN = PropertyFactory.regexProperty("testClassPattern")
.defaultValue("^(.*\\.)?Test.*$|^(.*\\.)?.*Tests?$|^(.*\\.)?.*TestCase$")
.desc("Test class name pattern to identify test classes by their fully qualified name. "
+ "A empty pattern disables test class detection by name. Since PMD 6.51.0.")
.build();

public TestClassWithoutTestCasesRule() {
addRuleChainVisit(ASTClassOrInterfaceBody.class);
definePropertyDescriptor(TEST_CLASS_PATTERN);
}

@Override
public Object visit(ASTClassOrInterfaceBody node, Object data) {
if (AbstractJUnitRule.isTestClass(node)) {
if (AbstractJUnitRule.isTestClass(node) || isTestClassByPattern(node)) {
List<ASTClassOrInterfaceBodyDeclaration> declarations = node.findChildrenOfType(ASTClassOrInterfaceBodyDeclaration.class);
int testMethods = 0;
for (ASTClassOrInterfaceBodyDeclaration decl : declarations) {
Expand All @@ -36,6 +48,36 @@ public Object visit(ASTClassOrInterfaceBody node, Object data) {
return data;
}

private boolean isTestClassByPattern(ASTClassOrInterfaceBody node) {
Pattern testClassPattern = getProperty(TEST_CLASS_PATTERN);
if (testClassPattern.pattern().isEmpty()) {
// detection by pattern is disabled
return false;
}

ASTClassOrInterfaceDeclaration classDecl = null;
if (node.getParent() instanceof ASTClassOrInterfaceDeclaration) {
classDecl = (ASTClassOrInterfaceDeclaration) node.getParent();
}

// classDecl can be null in case of anonymous classes or enum constants
if (classDecl == null || classDecl.isAbstract() || classDecl.isInterface()) {
return false;
}

StringBuilder fullyQualifiedName = new StringBuilder();
ASTPackageDeclaration packageDeclaration = classDecl.getRoot().getPackageDeclaration();
if (packageDeclaration != null) {
fullyQualifiedName.append(packageDeclaration.getName()).append('.');
}
List<ASTClassOrInterfaceDeclaration> parentClasses = classDecl.getParentsOfType(ASTClassOrInterfaceDeclaration.class);
for (int i = parentClasses.size() - 1; i >= 0; i--) {
fullyQualifiedName.append(parentClasses.get(i).getSimpleName()).append('.');
}
fullyQualifiedName.append(classDecl.getSimpleName());
return testClassPattern.matcher(fullyQualifiedName).find();
}

private boolean isTestMethod(ASTClassOrInterfaceBodyDeclaration decl) {
JavaNode node = decl.getDeclarationNode();
if (node instanceof ASTMethodDeclaration) {
Expand Down
8 changes: 6 additions & 2 deletions 8 pmd-java/src/main/resources/category/java/errorprone.xml
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -3336,8 +3336,12 @@ public void foo() {
class="net.sourceforge.pmd.lang.java.rule.errorprone.TestClassWithoutTestCasesRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#testclasswithouttestcases">
<description>
Test classes end with the suffix Test. Having a non-test class with that name is not a good practice,
since most people will assume it is a test case. Test classes have test methods named testXXX.
Test classes end with the suffix "Test" or "TestCase". Having a non-test class with that name is not a good practice,
since most people will assume it is a test case. Test classes have test methods named "testXXX" (JUnit3) or use
annotations (e.g. `@Test`).

The suffix can be configured using the property `testClassPattern`. To disable the detection of possible test classes
by name, set this property to an empty string.
</description>
<priority>3</priority>
<example>
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.