Skip to content

Commit 50320c7

Browse files
authored
Merge pull request #2628 from aschackmull/java/no-adhoc-testclass
Java: Replace ad-hoc TestClass detection.
2 parents 33070cc + 0bbe571 commit 50320c7

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

change-notes/1.24/analysis-java.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,10 @@ The following changes in version 1.24 affect Java analysis in all applications.
2222

2323
## Changes to libraries
2424

25+
* Identification of test classes has been improved. Previously, one of the
26+
match conditions would classify any class with a name containing the string
27+
"Test" as a test class, but now this matching has been replaced with one that
28+
looks for the occurrence of actual unit-test annotations. This affects the
29+
general file classification mechanism and thus suppression of alerts, and
30+
also any security queries using taint tracking, as test classes act as
31+
default barriers stopping taint flow.

java/ql/src/semmle/code/java/UnitTests.qll

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,32 @@ class TearDownMethod extends Method {
3636
}
3737
}
3838

39+
private class TestRelatedAnnotation extends Annotation {
40+
TestRelatedAnnotation() {
41+
this.getType().getPackage().hasName("org.testng.annotations") or
42+
this.getType().getPackage().hasName("org.junit") or
43+
this.getType().getPackage().hasName("org.junit.runner") or
44+
this.getType().getPackage().hasName("org.junit.jupiter.api") or
45+
this.getType().getPackage().hasName("org.junit.jupiter.params")
46+
}
47+
}
48+
49+
private class TestRelatedMethod extends Method {
50+
TestRelatedMethod() { this.getAnAnnotation() instanceof TestRelatedAnnotation }
51+
}
52+
3953
/**
40-
* A class detected to be a test class, either because it is a JUnit test class
41-
* or because its name or the name of one of its super-types contains the substring "Test".
54+
* A class detected to be a test class, either because it or one of its super-types
55+
* and/or enclosing types contains a test method or method with a unit-test-related
56+
* annotation.
4257
*/
4358
class TestClass extends Class {
4459
TestClass() {
4560
this instanceof JUnit38TestClass or
46-
this.getASupertype*().getSourceDeclaration().getName().matches("%Test%")
61+
exists(TestMethod m | m.getDeclaringType() = this) or
62+
exists(TestRelatedMethod m | m.getDeclaringType() = this) or
63+
this.getASourceSupertype() instanceof TestClass or
64+
this.getEnclosingType() instanceof TestClass
4765
}
4866
}
4967

0 commit comments

Comments
 (0)