mirror of
https://github.com/jlengrand/error-prone-support.git
synced 2026-03-10 15:49:33 +00:00
Compare commits
153 Commits
rossendrij
...
sschroever
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
689eac7c8d | ||
|
|
7c3abaec21 | ||
|
|
d260112bed | ||
|
|
a074e2fdd6 | ||
|
|
f06d4e41cf | ||
|
|
cf7bb657fa | ||
|
|
8277b43955 | ||
|
|
691f2c8311 | ||
|
|
362518b0f4 | ||
|
|
b9a3840e25 | ||
|
|
14d8bddbec | ||
|
|
6c7a0b81ea | ||
|
|
3a3825f7ba | ||
|
|
31e54cc990 | ||
|
|
775a2688ca | ||
|
|
3d854a0cc5 | ||
|
|
6ee013da58 | ||
|
|
962d18dcb5 | ||
|
|
aab308a190 | ||
|
|
009bd5d0d7 | ||
|
|
8e57f64e31 | ||
|
|
53e81f3611 | ||
|
|
8745105251 | ||
|
|
3eb3c20b1d | ||
|
|
121618f277 | ||
|
|
5cf4194168 | ||
|
|
c434cd318c | ||
|
|
22aa9cb213 | ||
|
|
3edc483e7c | ||
|
|
fff5d7b329 | ||
|
|
4ca80952ab | ||
|
|
8cecb8bf30 | ||
|
|
a937bf0ddf | ||
|
|
0b71c2b576 | ||
|
|
239d38d69f | ||
|
|
ab57aa5eb6 | ||
|
|
49267337cb | ||
|
|
c201fe1fd2 | ||
|
|
fb20b6f93d | ||
|
|
9264c25b57 | ||
|
|
ca628eef6c | ||
|
|
62168dcd4b | ||
|
|
96a82eaf85 | ||
|
|
0c615b4c15 | ||
|
|
6304130ae3 | ||
|
|
1674e99ba4 | ||
|
|
75bbc8e5b5 | ||
|
|
fe3ed2be63 | ||
|
|
f36350f3ba | ||
|
|
4888ad3aaf | ||
|
|
9daf73f148 | ||
|
|
b08ca514c1 | ||
|
|
4eed7dd0e8 | ||
|
|
618c62e7a5 | ||
|
|
b46f075ddf | ||
|
|
64436ff9b6 | ||
|
|
e028077f1e | ||
|
|
5aa386b5ba | ||
|
|
a480fe908d | ||
|
|
b2316c744c | ||
|
|
9334babfe8 | ||
|
|
b6632d393b | ||
|
|
53d191ff4f | ||
|
|
b8ddf3ac20 | ||
|
|
e859c2774f | ||
|
|
1cb4ce97ae | ||
|
|
92fe96286f | ||
|
|
d7531abceb | ||
|
|
cc7074a62f | ||
|
|
91922454b6 | ||
|
|
eaa98c985c | ||
|
|
94908d6a37 | ||
|
|
e8d9221424 | ||
|
|
fea8f5b2c0 | ||
|
|
2199accedc | ||
|
|
83670aeddf | ||
|
|
e8977bea67 | ||
|
|
0d051064bb | ||
|
|
06913b6a5b | ||
|
|
d2bbee3ed9 | ||
|
|
793a70c29b | ||
|
|
63b4fae185 | ||
|
|
73f8f056b4 | ||
|
|
c1638066cd | ||
|
|
08e99fb54e | ||
|
|
00012c6aa8 | ||
|
|
193589d193 | ||
|
|
1a1588d413 | ||
|
|
6656bd8186 | ||
|
|
26a9b46de7 | ||
|
|
17e74f778b | ||
|
|
e1bdb098de | ||
|
|
0be162c837 | ||
|
|
edfb2a70e8 | ||
|
|
c1e5dc4339 | ||
|
|
7218006b3c | ||
|
|
a3f599ba1b | ||
|
|
f819a3e42f | ||
|
|
7fc865c769 | ||
|
|
0287060d96 | ||
|
|
ac4e81f2c7 | ||
|
|
350f028781 | ||
|
|
299ce7b800 | ||
|
|
f3a929a3bb | ||
|
|
625a55add5 | ||
|
|
ef59340987 | ||
|
|
f2aea38b17 | ||
|
|
5cd8863eb5 | ||
|
|
5b57b4720b | ||
|
|
5224571407 | ||
|
|
c8189e9431 | ||
|
|
0fe42f1ea6 | ||
|
|
78b29107a3 | ||
|
|
7ae7d5105a | ||
|
|
0976b33d61 | ||
|
|
4b6f81c4fa | ||
|
|
1e879c175e | ||
|
|
d014fed400 | ||
|
|
1357f60fbc | ||
|
|
03abbbf99c | ||
|
|
9b845782c2 | ||
|
|
08ce33fb19 | ||
|
|
182724bc8e | ||
|
|
e9d361713a | ||
|
|
b754880556 | ||
|
|
affd5c7b93 | ||
|
|
d86611e66a | ||
|
|
2d6100a679 | ||
|
|
912797a55a | ||
|
|
d097f31124 | ||
|
|
eb05582f79 | ||
|
|
964fc35b71 | ||
|
|
ddc05bf88c | ||
|
|
24afa6a755 | ||
|
|
8e97121bdf | ||
|
|
567c81a93d | ||
|
|
c0bfac7b4c | ||
|
|
28138f35eb | ||
|
|
a9b691b856 | ||
|
|
acfe87fbc4 | ||
|
|
091a6eee7a | ||
|
|
3c06e3ead3 | ||
|
|
3ecab2f4b9 | ||
|
|
4b3e79667d | ||
|
|
6505535525 | ||
|
|
e48bbf3a44 | ||
|
|
3391468746 | ||
|
|
10172c426d | ||
|
|
f2737b4fe9 | ||
|
|
f9a1c82d68 | ||
|
|
cbc886d0c2 | ||
|
|
e4e3aded84 | ||
|
|
e84d0e1059 |
10
.mvn/jvm.config
Normal file
10
.mvn/jvm.config
Normal file
@@ -0,0 +1,10 @@
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED
|
||||
--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
|
||||
--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
|
||||
--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED
|
||||
@@ -11,10 +11,11 @@ install:
|
||||
script:
|
||||
# We run the build twice: once against the original Error Prone release,
|
||||
# using only Error Prone checks available on Maven Central, and once against
|
||||
# the Picnic Error Prone fork, additionally enabling Error Prone checks
|
||||
# available from other artifact repositories.
|
||||
# the Picnic Error Prone fork, additionally enabling all checks defined in
|
||||
# this project and any Error Prone checks available only from other artifact
|
||||
# repositories.
|
||||
- ./mvnw clean install
|
||||
- ./mvnw clean install -Perror-prone-fork -Pnon-maven-central -s settings.xml
|
||||
- ./mvnw clean install -Perror-prone-fork -Pnon-maven-central -Pself-check -s settings.xml
|
||||
# XXX: Enable SonarCloud once we "go public".
|
||||
# ./mvnw jacoco:prepare-agent surefire:test jacoco:report sonar:sonar
|
||||
- ./mvnw jacoco:prepare-agent surefire:test jacoco:report
|
||||
|
||||
@@ -276,10 +276,6 @@ Refaster's expressiveness:
|
||||
to be lost. In such a case don't statically import the method, so that the
|
||||
generic type information can be retained. (There may be cases where generic
|
||||
type information should even be _added_. Find an example.)
|
||||
- Upon application of a template Refaster can throw a _No binding for
|
||||
Key{identifier=someAfterTemplateParam}_ exception. When this happens the
|
||||
template is invalid. Instead perform this check at compile time, such that
|
||||
such malformed templates cannot be defined in the first place.
|
||||
- Provide a way to express "match if (not) annotated (with _X_)". See #1 for a
|
||||
motivating example.
|
||||
- Provide a way to place match constraints on compile time constants. For
|
||||
|
||||
@@ -39,19 +39,33 @@
|
||||
<artifactId>error_prone_test_helpers</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- XXX: dubious. -->
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>refaster-resource-compiler</artifactId>
|
||||
<artifactId>plexus-compiler-javac-caching</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>refaster-compiler</artifactId>
|
||||
<!-- This dependency is declared only as a hint to Maven that
|
||||
compilation depends on it; see the `maven-compiler-plugin`'s
|
||||
`annotationProcessorPaths` configuration below. -->
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>refaster-support</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.auto</groupId>
|
||||
<artifactId>auto-common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.auto.service</groupId>
|
||||
<artifactId>auto-service-annotations</artifactId>
|
||||
@@ -72,6 +86,11 @@
|
||||
<artifactId>guava</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.newrelic.agent.java</groupId>
|
||||
<artifactId>newrelic-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
@@ -122,11 +141,6 @@
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
@@ -159,18 +173,18 @@
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<scope>test</scope>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<scope>test</scope>
|
||||
<artifactId>spring-webflux</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<scope>test</scope>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-test</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
@@ -183,7 +197,7 @@
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>com.coveo</groupId>
|
||||
<groupId>com.spotify.fmt</groupId>
|
||||
<artifactId>fmt-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<additionalSourceDirectories>
|
||||
@@ -198,15 +212,31 @@
|
||||
<annotationProcessorPaths combine.children="append">
|
||||
<path>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>refaster-resource-compiler</artifactId>
|
||||
<artifactId>refaster-compiler</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</path>
|
||||
<path>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>refaster-support</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<compilerArgs combine.children="append">
|
||||
<arg>-Xplugin:RefasterRuleResourceCompiler</arg>
|
||||
<arg>-Xplugin:RefasterRuleCompiler</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<configuration>
|
||||
<ignoredUnusedDeclaredDependencies>
|
||||
<!-- XXX: Figure out why the plugin thinks this
|
||||
dependency is unused. -->
|
||||
<ignoredUnusedDeclaredDependency>${project.groupId}:refaster-support</ignoredUnusedDeclaredDependency>
|
||||
</ignoredUnusedDeclaredDependencies>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.AnnotationTree;
|
||||
import com.sun.source.tree.ClassTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
import com.sun.tools.javac.code.Symbol;
|
||||
import java.util.Map;
|
||||
import javax.lang.model.element.AnnotationValue;
|
||||
|
||||
/** A {@link BugChecker} which flags ambiguous {@code @JsonCreator}s in enums. */
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "AmbiguousJsonCreator",
|
||||
summary = "`JsonCreator.Mode` should be set for single-argument creators",
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class AmbiguousJsonCreatorCheck extends BugChecker implements AnnotationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<AnnotationTree> IS_JSON_CREATOR_ANNOTATION =
|
||||
isType("com.fasterxml.jackson.annotation.JsonCreator");
|
||||
|
||||
@Override
|
||||
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
|
||||
if (!IS_JSON_CREATOR_ANNOTATION.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
ClassTree clazz = state.findEnclosing(ClassTree.class);
|
||||
if (clazz == null || clazz.getKind() != Tree.Kind.ENUM) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
MethodTree method = state.findEnclosing(MethodTree.class);
|
||||
if (method == null || method.getParameters().size() != 1) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
boolean customMode =
|
||||
ASTHelpers.getAnnotationMirror(tree).getElementValues().entrySet().stream()
|
||||
.filter(entry -> entry.getKey().getSimpleName().contentEquals("mode"))
|
||||
.map(Map.Entry::getValue)
|
||||
.map(AnnotationValue::getValue)
|
||||
.filter(Symbol.VarSymbol.class::isInstance)
|
||||
.map(Symbol.VarSymbol.class::cast)
|
||||
.anyMatch(varSymbol -> !varSymbol.getSimpleName().contentEquals("DEFAULT"));
|
||||
|
||||
return customMode
|
||||
? Description.NO_MATCH
|
||||
: describeMatch(
|
||||
tree, SuggestedFix.replace(tree, "@JsonCreator(mode = JsonCreator.Mode.DELEGATING)"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
@@ -7,9 +10,6 @@ import static com.google.errorprone.matchers.Matchers.isType;
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
|
||||
@@ -28,9 +28,9 @@ import java.util.List;
|
||||
@BugPattern(
|
||||
name = "AutowiredConstructor",
|
||||
summary = "Omit `@Autowired` on a class' sole constructor, as it is redundant",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class AutowiredConstructorCheck extends BugChecker implements ClassTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final MultiMatcher<Tree, AnnotationTree> AUTOWIRED_ANNOTATION =
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
|
||||
@@ -30,9 +31,9 @@ import java.util.regex.Pattern;
|
||||
@BugPattern(
|
||||
name = "CanonicalAnnotationSyntax",
|
||||
summary = "Omit redundant syntax from annotation declarations",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class CanonicalAnnotationSyntaxCheck extends BugChecker
|
||||
implements AnnotationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.common.hash.Hashing;
|
||||
import com.google.common.reflect.ClassPath;
|
||||
import java.io.IOException;
|
||||
|
||||
final class CodeTransformers {
|
||||
// XXX: Use.
|
||||
private static void foo(ClassPath.ResourceInfo resource) {
|
||||
try {
|
||||
resource.asByteSource().hash(Hashing.murmur3_32_fixed(0)).toString();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
@@ -7,9 +10,6 @@ import static com.google.errorprone.matchers.Matchers.isType;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
|
||||
@@ -17,21 +17,23 @@ import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.ClassTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
import com.sun.tools.javac.code.Symbol.MethodSymbol;
|
||||
import java.util.Optional;
|
||||
|
||||
/** A {@link BugChecker} which flags empty methods that seemingly can simply be deleted. */
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "EmptyMethod",
|
||||
summary = "Empty method can likely be deleted",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class EmptyMethodCheck extends BugChecker implements MethodTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<Tree> HAS_PERMITTED_ANNOTATION =
|
||||
private static final Matcher<Tree> PERMITTED_ANNOTATION =
|
||||
annotations(
|
||||
AT_LEAST_ONE,
|
||||
anyOf(isType("java.lang.Override"), isType("org.aspectj.lang.annotation.Pointcut")));
|
||||
@@ -41,7 +43,8 @@ public final class EmptyMethodCheck extends BugChecker implements MethodTreeMatc
|
||||
if (tree.getBody() == null
|
||||
|| !tree.getBody().getStatements().isEmpty()
|
||||
|| ASTHelpers.containsComments(tree, state)
|
||||
|| HAS_PERMITTED_ANNOTATION.matches(tree, state)) {
|
||||
|| PERMITTED_ANNOTATION.matches(tree, state)
|
||||
|| isInPossibleTestHelperClass(state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
@@ -52,4 +55,11 @@ public final class EmptyMethodCheck extends BugChecker implements MethodTreeMatc
|
||||
|
||||
return describeMatch(tree, SuggestedFix.delete(tree));
|
||||
}
|
||||
|
||||
private static boolean isInPossibleTestHelperClass(VisitorState state) {
|
||||
return Optional.ofNullable(ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class))
|
||||
.map(ClassTree::getSimpleName)
|
||||
.filter(name -> name.toString().contains("Test"))
|
||||
.isPresent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSetMultimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import com.sun.tools.javac.code.Symbol;
|
||||
import com.sun.tools.javac.code.Type;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags {@link Ordering#explicit(Object, Object[])}} invocations listing
|
||||
* a subset of an enum type's values.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "ExplicitEnumOrdering",
|
||||
summary = "Make sure `Ordering#explicit` lists all of an enum's values",
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = FRAGILE_CODE)
|
||||
public final class ExplicitEnumOrderingCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<ExpressionTree> EXPLICIT_ORDERING =
|
||||
staticMethod().onClass(Ordering.class.getName()).named("explicit");
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
if (!EXPLICIT_ORDERING.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
ImmutableSet<String> missingEnumValues = getMissingEnumValues(tree.getArguments());
|
||||
if (missingEnumValues.isEmpty()) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
return buildDescription(tree)
|
||||
.setMessage(
|
||||
String.format(
|
||||
"Explicit ordering lacks some enum values: %s",
|
||||
String.join(", ", missingEnumValues)))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ImmutableSet<String> getMissingEnumValues(
|
||||
List<? extends ExpressionTree> expressions) {
|
||||
return expressions.stream()
|
||||
.map(ASTHelpers::getSymbol)
|
||||
.filter(Symbol::isEnum)
|
||||
.collect(
|
||||
collectingAndThen(
|
||||
toImmutableSetMultimap(Symbol::asType, Symbol::toString),
|
||||
ExplicitEnumOrderingCheck::getMissingEnumValues));
|
||||
}
|
||||
|
||||
private static ImmutableSet<String> getMissingEnumValues(
|
||||
ImmutableSetMultimap<Type, String> valuesByType) {
|
||||
return Multimaps.asMap(valuesByType).entrySet().stream()
|
||||
.flatMap(e -> getMissingEnumValues(e.getKey(), e.getValue()))
|
||||
.collect(toImmutableSet());
|
||||
}
|
||||
|
||||
private static Stream<String> getMissingEnumValues(Type enumType, Set<String> values) {
|
||||
Symbol.TypeSymbol typeSymbol = enumType.asElement();
|
||||
return Sets.difference(ASTHelpers.enumValues(typeSymbol), values).stream()
|
||||
.map(v -> String.format("%s.%s", typeSymbol.getSimpleName(), v));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.fixes.SuggestedFixes;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MemberReferenceTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags usages of {@link Flux#flatMap(Function)} and {@link
|
||||
* Flux#flatMapSequential(Function)}.
|
||||
*
|
||||
* <p>{@link Flux#flatMap(Function)} and {@link Flux#flatMapSequential(Function)} eagerly perform up
|
||||
* to {@link reactor.util.concurrent.Queues#SMALL_BUFFER_SIZE} subscriptions. Additionally, the
|
||||
* former interleaves values as they are emitted, yielding nondeterministic results. In most cases
|
||||
* {@link Flux#concatMap(Function)} should be preferred, as it produces consistent results and
|
||||
* avoids potentially saturating the thread pool on which subscription happens. If {@code
|
||||
* concatMap}'s single-subscription semantics are undesirable one should invoke a {@code flatMap} or
|
||||
* {@code flatMapSequential} overload with an explicit concurrency level.
|
||||
*
|
||||
* <p>NB: The rarely-used overload {@link Flux#flatMap(Function, Function, Supplier)} is not flagged
|
||||
* by this check because there is no clear alternative to point to.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "FluxFlatMapUsage",
|
||||
summary =
|
||||
"`Flux#flatMap` and `Flux#flatMapSequential` have subtle semantics; "
|
||||
+ "please use `Flux#concatMap` or explicitly specify the desired amount of concurrency",
|
||||
linkType = NONE,
|
||||
severity = ERROR,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class FluxFlatMapUsageCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher, MemberReferenceTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String MAX_CONCURRENCY_ARG_NAME = "MAX_CONCURRENCY";
|
||||
private static final Matcher<ExpressionTree> FLUX_FLATMAP =
|
||||
instanceMethod()
|
||||
.onDescendantOf("reactor.core.publisher.Flux")
|
||||
.namedAnyOf("flatMap", "flatMapSequential")
|
||||
.withParameters(Function.class.getName());
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
if (!FLUX_FLATMAP.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
return buildDescription(tree)
|
||||
.addFix(SuggestedFixes.renameMethodInvocation(tree, "concatMap", state))
|
||||
.addFix(
|
||||
SuggestedFix.builder()
|
||||
.postfixWith(
|
||||
Iterables.getOnlyElement(tree.getArguments()), ", " + MAX_CONCURRENCY_ARG_NAME)
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
|
||||
if (!FLUX_FLATMAP.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
// Method references are expected to occur very infrequently; generating both variants of
|
||||
// suggested fixes is not worth the trouble.
|
||||
return describeMatch(tree);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.Matchers.allOf;
|
||||
import static com.google.errorprone.matchers.Matchers.anyMethod;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.instanceMethod;
|
||||
import static com.google.errorprone.matchers.Matchers.not;
|
||||
import static com.google.errorprone.matchers.Matchers.staticMethod;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.BinaryTree;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.LiteralTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import com.sun.source.tree.ParenthesizedTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
import com.sun.source.tree.Tree.Kind;
|
||||
import com.sun.source.util.SimpleTreeVisitor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags string concatenations that produce a format string; in such
|
||||
* cases the string concatenation should instead be deferred to the invoked method.
|
||||
*
|
||||
* @implNote This checker is based on the implementation of {@link
|
||||
* com.google.errorprone.bugpatterns.flogger.FloggerStringConcatenation}.
|
||||
*/
|
||||
// XXX: Support arbitrary `@FormatMethod`-annotated methods.
|
||||
// XXX: For (explicit or delegated) invocations of `java.util.Formatter` _strictly speaking_ we
|
||||
// should introduce special handling of `Formattable` arguments, as this check would replace a
|
||||
// `Formattable#toString` invocation with a `Formattable#formatTo` invocation. But likely that
|
||||
// should be considered a bug fix, too.
|
||||
// XXX: Introduce a separate check which adds/removes the `Locale` parameter to `String.format`
|
||||
// invocations, as necessary.
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "FormatStringConcatenation",
|
||||
summary = "Defer string concatenation to the invoked method",
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class FormatStringConcatenationCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
/**
|
||||
* AssertJ exposes varargs {@code fail} methods with a {@link Throwable}-accepting overload, the
|
||||
* latter of which should not be flagged.
|
||||
*/
|
||||
private static final Matcher<ExpressionTree> ASSERTJ_FAIL_WITH_THROWABLE_METHOD =
|
||||
anyMethod()
|
||||
.anyClass()
|
||||
.withAnyName()
|
||||
.withParameters(String.class.getName(), Throwable.class.getName());
|
||||
// XXX: Drop some of these methods if we use Refaster to replace some with others.
|
||||
private static final Matcher<ExpressionTree> ASSERTJ_FORMAT_METHOD =
|
||||
anyOf(
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.AbstractAssert")
|
||||
.namedAnyOf("overridingErrorMessage", "withFailMessage"),
|
||||
allOf(
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.AbstractSoftAssertions")
|
||||
.named("fail"),
|
||||
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)),
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.AbstractStringAssert")
|
||||
.named("isEqualTo"),
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.AbstractThrowableAssert")
|
||||
.namedAnyOf(
|
||||
"hasMessage",
|
||||
"hasMessageContaining",
|
||||
"hasMessageEndingWith",
|
||||
"hasMessageStartingWith",
|
||||
"hasRootCauseMessage",
|
||||
"hasStackTraceContaining"),
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.Descriptable")
|
||||
.namedAnyOf("as", "describedAs"),
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.assertj.core.api.ThrowableAssertAlternative")
|
||||
.namedAnyOf(
|
||||
"withMessage",
|
||||
"withMessageContaining",
|
||||
"withMessageEndingWith",
|
||||
"withMessageStartingWith",
|
||||
"withStackTraceContaining"),
|
||||
allOf(
|
||||
instanceMethod().onDescendantOf("org.assertj.core.api.WithAssertions").named("fail"),
|
||||
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)),
|
||||
allOf(
|
||||
staticMethod()
|
||||
.onClassAny(
|
||||
"org.assertj.core.api.Assertions",
|
||||
"org.assertj.core.api.BDDAssertions",
|
||||
"org.assertj.core.api.Fail")
|
||||
.named("fail"),
|
||||
not(ASSERTJ_FAIL_WITH_THROWABLE_METHOD)));
|
||||
private static final Matcher<ExpressionTree> GUAVA_FORMAT_METHOD =
|
||||
anyOf(
|
||||
staticMethod()
|
||||
.onClass("com.google.common.base.Preconditions")
|
||||
.namedAnyOf("checkArgument", "checkNotNull", "checkState"),
|
||||
staticMethod().onClass("com.google.common.base.Verify").named("verify"));
|
||||
// XXX: Add `PrintWriter`, maybe others.
|
||||
private static final Matcher<ExpressionTree> JDK_FORMAT_METHOD =
|
||||
anyOf(
|
||||
staticMethod().onClass("java.lang.String").named("format"),
|
||||
instanceMethod().onExactClass("java.util.Formatter").named("format"));
|
||||
private static final Matcher<ExpressionTree> SLF4J_FORMAT_METHOD =
|
||||
instanceMethod()
|
||||
.onDescendantOf("org.slf4j.Logger")
|
||||
.namedAnyOf("debug", "error", "info", "trace", "warn");
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
if (hasNonConstantStringConcatenationArgument(tree, 0, state)) {
|
||||
return flagViolation(tree, ASSERTJ_FORMAT_METHOD, 0, "%s", state)
|
||||
.or(() -> flagViolation(tree, JDK_FORMAT_METHOD, 0, "%s", state))
|
||||
.or(() -> flagViolation(tree, SLF4J_FORMAT_METHOD, 0, "{}", state))
|
||||
.orElse(Description.NO_MATCH);
|
||||
}
|
||||
|
||||
if (hasNonConstantStringConcatenationArgument(tree, 1, state)) {
|
||||
return flagViolation(tree, GUAVA_FORMAT_METHOD, 1, "%s", state)
|
||||
.or(() -> flagViolation(tree, JDK_FORMAT_METHOD, 1, "%s", state))
|
||||
.or(() -> flagViolation(tree, SLF4J_FORMAT_METHOD, 1, "{}", state))
|
||||
.orElse(Description.NO_MATCH);
|
||||
}
|
||||
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flags the given method invocation if it matches a targeted method and passes a non-compile time
|
||||
* constant string concatenation as a format string.
|
||||
*/
|
||||
private Optional<Description> flagViolation(
|
||||
MethodInvocationTree tree,
|
||||
Matcher<ExpressionTree> matcher,
|
||||
int formatStringParam,
|
||||
String formatSpecifier,
|
||||
VisitorState state) {
|
||||
if (!matcher.matches(tree, state)) {
|
||||
/* The invoked method is not targeted by this check. */
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<? extends ExpressionTree> arguments = tree.getArguments();
|
||||
|
||||
if (arguments.size() > formatStringParam + 1) {
|
||||
/*
|
||||
* This method invocation uses explicit string concatenation but _also_ already relies on
|
||||
* format specifiers: flag but don't suggest a fix.
|
||||
*/
|
||||
return Optional.of(describeMatch(tree));
|
||||
}
|
||||
|
||||
ExpressionTree formatStringArg = arguments.get(formatStringParam);
|
||||
ReplacementArgumentsConstructor replacementConstructor =
|
||||
new ReplacementArgumentsConstructor(formatSpecifier);
|
||||
formatStringArg.accept(replacementConstructor, state);
|
||||
|
||||
return Optional.of(
|
||||
describeMatch(
|
||||
tree,
|
||||
SuggestedFix.replace(
|
||||
formatStringArg, replacementConstructor.getReplacementArguments(state))));
|
||||
}
|
||||
|
||||
private static boolean hasNonConstantStringConcatenationArgument(
|
||||
MethodInvocationTree tree, int argPosition, VisitorState state) {
|
||||
List<? extends ExpressionTree> arguments = tree.getArguments();
|
||||
if (arguments.size() <= argPosition) {
|
||||
/* This method doesn't accept enough parameters. */
|
||||
return false;
|
||||
}
|
||||
|
||||
ExpressionTree argument = ASTHelpers.stripParentheses(arguments.get(argPosition));
|
||||
return argument instanceof BinaryTree
|
||||
&& isStringTyped(argument, state)
|
||||
&& ASTHelpers.constValue(argument, String.class) == null;
|
||||
}
|
||||
|
||||
private static boolean isStringTyped(ExpressionTree tree, VisitorState state) {
|
||||
return ASTHelpers.isSameType(ASTHelpers.getType(tree), state.getSymtab().stringType, state);
|
||||
}
|
||||
|
||||
private static class ReplacementArgumentsConstructor
|
||||
extends SimpleTreeVisitor<Void, VisitorState> {
|
||||
private final StringBuilder formatString = new StringBuilder();
|
||||
private final List<Tree> formatArguments = new ArrayList<>();
|
||||
private final String formatSpecifier;
|
||||
|
||||
ReplacementArgumentsConstructor(String formatSpecifier) {
|
||||
this.formatSpecifier = formatSpecifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Void visitBinary(BinaryTree tree, VisitorState state) {
|
||||
if (tree.getKind() == Kind.PLUS && isStringTyped(tree, state)) {
|
||||
tree.getLeftOperand().accept(this, state);
|
||||
tree.getRightOperand().accept(this, state);
|
||||
} else {
|
||||
appendExpression(tree);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Void visitParenthesized(ParenthesizedTree tree, VisitorState state) {
|
||||
return tree.getExpression().accept(this, state);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Void defaultAction(Tree tree, VisitorState state) {
|
||||
appendExpression(tree);
|
||||
return null;
|
||||
}
|
||||
|
||||
private void appendExpression(Tree tree) {
|
||||
if (tree instanceof LiteralTree) {
|
||||
formatString.append(((LiteralTree) tree).getValue());
|
||||
} else {
|
||||
formatString.append(formatSpecifier);
|
||||
formatArguments.add(tree);
|
||||
}
|
||||
}
|
||||
|
||||
private String getReplacementArguments(VisitorState state) {
|
||||
return state.getConstantExpression(formatString.toString())
|
||||
+ ", "
|
||||
+ formatArguments.stream()
|
||||
.map(tree -> Util.treeToString(tree, state))
|
||||
.collect(joining(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.staticMethod;
|
||||
import static com.google.errorprone.suppliers.Suppliers.OBJECT_TYPE;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.primitives.Primitives;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.bugpatterns.TypesWithUndefinedEquality;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.fixes.SuggestedFixes;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.google.errorprone.util.ASTHelpers.TargetType;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import com.sun.tools.javac.code.Type;
|
||||
import com.sun.tools.javac.code.Types;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/** A {@link BugChecker} that flags redundant identity conversions. */
|
||||
// XXX: Consider detecting cases where a flagged expression is passed to a method, and where removal
|
||||
// of the identify conversion would cause a different method overload to be selected. Depending on
|
||||
// the target method such a modification may change the code's semantics or performance.
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "IdentityConversion",
|
||||
summary = "Avoid or clarify identity conversions",
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class IdentityConversionCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<ExpressionTree> IS_CONVERSION_METHOD =
|
||||
anyOf(
|
||||
staticMethod()
|
||||
.onClassAny(
|
||||
"com.google.common.collect.ImmutableBiMap",
|
||||
"com.google.common.collect.ImmutableList",
|
||||
"com.google.common.collect.ImmutableListMultimap",
|
||||
"com.google.common.collect.ImmutableMap",
|
||||
"com.google.common.collect.ImmutableMultimap",
|
||||
"com.google.common.collect.ImmutableMultiset",
|
||||
"com.google.common.collect.ImmutableRangeMap",
|
||||
"com.google.common.collect.ImmutableRangeSet",
|
||||
"com.google.common.collect.ImmutableSet",
|
||||
"com.google.common.collect.ImmutableSetMultimap",
|
||||
"com.google.common.collect.ImmutableTable")
|
||||
.named("copyOf"),
|
||||
staticMethod()
|
||||
.onClassAny(
|
||||
Primitives.allWrapperTypes().stream()
|
||||
.map(Class::getName)
|
||||
.collect(toImmutableSet()))
|
||||
.named("valueOf"),
|
||||
staticMethod().onClass(String.class.getName()).named("valueOf"),
|
||||
staticMethod().onClass("reactor.adapter.rxjava.RxJava2Adapter"),
|
||||
staticMethod()
|
||||
.onClass("reactor.core.publisher.Flux")
|
||||
.namedAnyOf("concat", "firstWithSignal", "from", "merge"),
|
||||
staticMethod().onClass("reactor.core.publisher.Mono").namedAnyOf("from", "fromDirect"));
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
List<? extends ExpressionTree> arguments = tree.getArguments();
|
||||
if (arguments.size() != 1 || !IS_CONVERSION_METHOD.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
ExpressionTree sourceTree = arguments.get(0);
|
||||
Type sourceType = ASTHelpers.getType(sourceTree);
|
||||
Type resultType = ASTHelpers.getType(tree);
|
||||
TargetType targetType = ASTHelpers.targetType(state);
|
||||
if (sourceType == null || resultType == null || targetType == null) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
if (!state.getTypes().isSameType(sourceType, resultType)
|
||||
&& !isConvertibleWithWellDefinedEquality(sourceType, targetType.type(), state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
return buildDescription(tree)
|
||||
.setMessage(
|
||||
"This method invocation appears redundant; remove it or suppress this warning and "
|
||||
+ "add a comment explaining its purpose")
|
||||
.addFix(SuggestedFix.replace(tree, Util.treeToString(sourceTree, state)))
|
||||
.addFix(SuggestedFixes.addSuppressWarnings(state, canonicalName()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static boolean isConvertibleWithWellDefinedEquality(
|
||||
Type sourceType, Type targetType, VisitorState state) {
|
||||
Types types = state.getTypes();
|
||||
return !types.isSameType(targetType, OBJECT_TYPE.get(state))
|
||||
&& types.isConvertible(sourceType, targetType)
|
||||
&& Arrays.stream(TypesWithUndefinedEquality.values())
|
||||
.noneMatch(b -> b.matchesType(sourceType, state) || b.matchesType(targetType, state));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.allOf;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.enclosingClass;
|
||||
import static com.google.errorprone.matchers.Matchers.hasModifier;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
import static java.util.function.Predicate.not;
|
||||
import static tech.picnic.errorprone.bugpatterns.JavaKeywords.isReservedKeyword;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
@@ -16,14 +23,19 @@ import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.fixes.SuggestedFixes;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.matchers.Matchers;
|
||||
import com.google.errorprone.matchers.MultiMatcher;
|
||||
import com.google.errorprone.predicates.TypePredicate;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.AnnotationTree;
|
||||
import com.sun.source.tree.ClassTree;
|
||||
import com.sun.source.tree.ImportTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
import com.sun.tools.javac.code.Symbol;
|
||||
import java.util.Optional;
|
||||
import javax.lang.model.element.Modifier;
|
||||
import javax.lang.model.element.Name;
|
||||
|
||||
/** A {@link BugChecker} which flags non-canonical JUnit method declarations. */
|
||||
// XXX: Consider introducing a class-level check which enforces that test classes:
|
||||
@@ -35,23 +47,28 @@ import javax.lang.model.element.Modifier;
|
||||
@BugPattern(
|
||||
name = "JUnitMethodDeclaration",
|
||||
summary = "JUnit method declaration can likely be improved",
|
||||
linkType = BugPattern.LinkType.NONE,
|
||||
severity = BugPattern.SeverityLevel.SUGGESTION,
|
||||
tags = BugPattern.StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class JUnitMethodDeclarationCheck extends BugChecker implements MethodTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String TEST_PREFIX = "test";
|
||||
private static final ImmutableSet<Modifier> ILLEGAL_MODIFIERS =
|
||||
ImmutableSet.of(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC);
|
||||
private static final MultiMatcher<MethodTree, AnnotationTree> IS_OVERRIDE_METHOD =
|
||||
annotations(AT_LEAST_ONE, isType("java.lang.Override"));
|
||||
private static final MultiMatcher<MethodTree, AnnotationTree> IS_TEST_METHOD =
|
||||
private static final Matcher<MethodTree> HAS_UNMODIFIABLE_SIGNATURE =
|
||||
anyOf(
|
||||
annotations(AT_LEAST_ONE, isType("java.lang.Override")),
|
||||
allOf(
|
||||
Matchers.not(hasModifier(Modifier.FINAL)),
|
||||
Matchers.not(hasModifier(Modifier.PRIVATE)),
|
||||
enclosingClass(hasModifier(Modifier.ABSTRACT))));
|
||||
private static final MultiMatcher<MethodTree, AnnotationTree> TEST_METHOD =
|
||||
annotations(
|
||||
AT_LEAST_ONE,
|
||||
anyOf(
|
||||
isType("org.junit.jupiter.api.Test"),
|
||||
hasMetaAnnotation("org.junit.jupiter.api.TestTemplate")));
|
||||
private static final MultiMatcher<MethodTree, AnnotationTree> IS_SETUP_OR_TEARDOWN_METHOD =
|
||||
private static final MultiMatcher<MethodTree, AnnotationTree> SETUP_OR_TEARDOWN_METHOD =
|
||||
annotations(
|
||||
AT_LEAST_ONE,
|
||||
anyOf(
|
||||
@@ -62,47 +79,117 @@ public final class JUnitMethodDeclarationCheck extends BugChecker implements Met
|
||||
|
||||
@Override
|
||||
public Description matchMethod(MethodTree tree, VisitorState state) {
|
||||
// XXX: Perhaps we should also skip analysis of non-`private` non-`final` methods in abstract
|
||||
// classes?
|
||||
if (IS_OVERRIDE_METHOD.matches(tree, state)) {
|
||||
if (HAS_UNMODIFIABLE_SIGNATURE.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
boolean isTestMethod = IS_TEST_METHOD.matches(tree, state);
|
||||
if (!isTestMethod && !IS_SETUP_OR_TEARDOWN_METHOD.matches(tree, state)) {
|
||||
boolean isTestMethod = TEST_METHOD.matches(tree, state);
|
||||
if (!isTestMethod && !SETUP_OR_TEARDOWN_METHOD.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
SuggestedFix.Builder builder = SuggestedFix.builder();
|
||||
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
|
||||
SuggestedFixes.removeModifiers(tree.getModifiers(), state, ILLEGAL_MODIFIERS)
|
||||
.ifPresent(builder::merge);
|
||||
.ifPresent(fixBuilder::merge);
|
||||
|
||||
if (isTestMethod) {
|
||||
// XXX: In theory this rename could clash with an existing method or static import. In that
|
||||
// case we should emit a warning without a suggested replacement.
|
||||
tryCanonicalizeMethodName(tree, state).ifPresent(builder::merge);
|
||||
suggestTestMethodRenameIfApplicable(tree, fixBuilder, state);
|
||||
}
|
||||
|
||||
return builder.isEmpty() ? Description.NO_MATCH : describeMatch(tree, builder.build());
|
||||
return fixBuilder.isEmpty() ? Description.NO_MATCH : describeMatch(tree, fixBuilder.build());
|
||||
}
|
||||
|
||||
private static Optional<SuggestedFix> tryCanonicalizeMethodName(
|
||||
MethodTree tree, VisitorState state) {
|
||||
private void suggestTestMethodRenameIfApplicable(
|
||||
MethodTree tree, SuggestedFix.Builder fixBuilder, VisitorState state) {
|
||||
tryCanonicalizeMethodName(tree)
|
||||
.ifPresent(
|
||||
newName ->
|
||||
findMethodRenameBlocker(newName, state)
|
||||
.ifPresentOrElse(
|
||||
blocker -> reportMethodRenameBlocker(tree, blocker, state),
|
||||
() -> fixBuilder.merge(SuggestedFixes.renameMethod(tree, newName, state))));
|
||||
}
|
||||
|
||||
private void reportMethodRenameBlocker(MethodTree tree, String reason, VisitorState state) {
|
||||
state.reportMatch(
|
||||
buildDescription(tree)
|
||||
.setMessage(
|
||||
String.format(
|
||||
"This method's name should not redundantly start with `%s` (but note that %s)",
|
||||
TEST_PREFIX, reason))
|
||||
.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* If applicable, returns a human-readable argument against assigning the given name to an
|
||||
* existing method.
|
||||
*
|
||||
* <p>This method implements imperfect heuristics. Things it currently does not consider include
|
||||
* the following:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Whether the rename would merely introduce a method overload, rather than clashing with an
|
||||
* existing method declaration.
|
||||
* <li>Whether the rename would cause a method in a superclass to be overridden.
|
||||
* <li>Whether the rename would in fact clash with a static import. (It could be that a static
|
||||
* import of the same name is only referenced from lexical scopes in which the method under
|
||||
* consideration cannot be referenced directly.)
|
||||
* </ul>
|
||||
*/
|
||||
private static Optional<String> findMethodRenameBlocker(String methodName, VisitorState state) {
|
||||
if (isMethodInEnclosingClass(methodName, state)) {
|
||||
return Optional.of(
|
||||
String.format("a method named `%s` already exists in this class", methodName));
|
||||
}
|
||||
|
||||
if (isSimpleNameStaticallyImported(methodName, state)) {
|
||||
return Optional.of(String.format("`%s` is already statically imported", methodName));
|
||||
}
|
||||
|
||||
if (isReservedKeyword(methodName)) {
|
||||
return Optional.of(String.format("`%s` is a reserved keyword", methodName));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static boolean isMethodInEnclosingClass(String methodName, VisitorState state) {
|
||||
return state.findEnclosing(ClassTree.class).getMembers().stream()
|
||||
.filter(MethodTree.class::isInstance)
|
||||
.map(MethodTree.class::cast)
|
||||
.map(MethodTree::getName)
|
||||
.map(Name::toString)
|
||||
.anyMatch(methodName::equals);
|
||||
}
|
||||
|
||||
private static boolean isSimpleNameStaticallyImported(String simpleName, VisitorState state) {
|
||||
return state.getPath().getCompilationUnit().getImports().stream()
|
||||
.filter(ImportTree::isStatic)
|
||||
.map(ImportTree::getQualifiedIdentifier)
|
||||
.map(tree -> getStaticImportSimpleName(tree, state))
|
||||
.anyMatch(simpleName::contentEquals);
|
||||
}
|
||||
|
||||
private static CharSequence getStaticImportSimpleName(Tree tree, VisitorState state) {
|
||||
String source = Util.treeToString(tree, state);
|
||||
return source.subSequence(source.lastIndexOf('.') + 1, source.length());
|
||||
}
|
||||
|
||||
private static Optional<String> tryCanonicalizeMethodName(MethodTree tree) {
|
||||
return Optional.ofNullable(ASTHelpers.getSymbol(tree))
|
||||
.map(sym -> sym.getQualifiedName().toString())
|
||||
.filter(name -> name.startsWith(TEST_PREFIX))
|
||||
.map(name -> name.substring(TEST_PREFIX.length()))
|
||||
.filter(not(String::isEmpty))
|
||||
.map(name -> Character.toLowerCase(name.charAt(0)) + name.substring(1))
|
||||
.filter(name -> !Character.isDigit(name.charAt(0)))
|
||||
.map(name -> SuggestedFixes.renameMethod(tree, name, state));
|
||||
.filter(name -> !Character.isDigit(name.charAt(0)));
|
||||
}
|
||||
|
||||
// XXX: Move to a `MoreMatchers` utility class.
|
||||
private static Matcher<AnnotationTree> hasMetaAnnotation(String annotationClassName) {
|
||||
TypePredicate typePredicate = hasAnnotation(annotationClassName);
|
||||
return (tree, state) -> {
|
||||
Symbol sym = ASTHelpers.getDeclaredSymbol(tree);
|
||||
Symbol sym = ASTHelpers.getSymbol(tree);
|
||||
return sym != null && typePredicate.apply(sym.type, state);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
final class JavaKeywords {
|
||||
/**
|
||||
* List of all reserved keywords in the Java language.
|
||||
*
|
||||
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.9">JDK 17 JLS
|
||||
* section 3.9: Keywords</a>
|
||||
*/
|
||||
private static final ImmutableSet<String> RESERVED_KEYWORDS =
|
||||
ImmutableSet.of(
|
||||
"_",
|
||||
"abstract",
|
||||
"assert",
|
||||
"boolean",
|
||||
"break",
|
||||
"byte",
|
||||
"case",
|
||||
"catch",
|
||||
"char",
|
||||
"class",
|
||||
"const",
|
||||
"continue",
|
||||
"default",
|
||||
"do",
|
||||
"double",
|
||||
"else",
|
||||
"enum",
|
||||
"extends",
|
||||
"final",
|
||||
"finally",
|
||||
"float",
|
||||
"for",
|
||||
"goto",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"instanceof",
|
||||
"int",
|
||||
"interface",
|
||||
"long",
|
||||
"native",
|
||||
"new",
|
||||
"package",
|
||||
"private",
|
||||
"protected",
|
||||
"public",
|
||||
"return",
|
||||
"short",
|
||||
"static",
|
||||
"strictfp",
|
||||
"super",
|
||||
"switch",
|
||||
"synchronized",
|
||||
"this",
|
||||
"throw",
|
||||
"throws",
|
||||
"transient",
|
||||
"try",
|
||||
"void",
|
||||
"volatile",
|
||||
"while");
|
||||
|
||||
/**
|
||||
* List of all contextual keywords in the Java language.
|
||||
*
|
||||
* @see <a href="https://docs.oracle.com/javase/specs/jls/se17/html/jls-3.html#jls-3.9">JDK 17 JLS
|
||||
* section 3.9: Keywords</a>
|
||||
*/
|
||||
private static final ImmutableSet<String> CONTEXTUAL_KEYWORDS =
|
||||
ImmutableSet.of(
|
||||
"exports",
|
||||
"module",
|
||||
"non-sealed",
|
||||
"open",
|
||||
"opens",
|
||||
"permits",
|
||||
"provides",
|
||||
"record",
|
||||
"requires",
|
||||
"sealed",
|
||||
"to",
|
||||
"transitive",
|
||||
"uses",
|
||||
"var",
|
||||
"with",
|
||||
"yield");
|
||||
|
||||
/** List of all keywords in the Java language. */
|
||||
private static final ImmutableSet<String> ALL_KEYWORDS =
|
||||
Sets.union(RESERVED_KEYWORDS, CONTEXTUAL_KEYWORDS).immutableCopy();
|
||||
|
||||
private JavaKeywords() {}
|
||||
|
||||
/** Tells whether the given string is a reserved keyword in the Java language. */
|
||||
public static boolean isReservedKeyword(String str) {
|
||||
return RESERVED_KEYWORDS.contains(str);
|
||||
}
|
||||
|
||||
/** Tells whether the given string is a contextual keyword in the Java language. */
|
||||
public static boolean isContextualKeyword(String str) {
|
||||
return CONTEXTUAL_KEYWORDS.contains(str);
|
||||
}
|
||||
|
||||
/** Tells whether the given string is a reserved or contextual keyword in the Java language. */
|
||||
public static boolean isKeyword(String str) {
|
||||
return ALL_KEYWORDS.contains(str);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
|
||||
import static java.util.Comparator.comparing;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
@@ -8,9 +12,6 @@ import com.google.common.collect.Comparators;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.ErrorProneFlags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
@@ -31,7 +32,6 @@ import com.sun.source.tree.Tree.Kind;
|
||||
import com.sun.source.util.TreeScanner;
|
||||
import com.sun.tools.javac.code.Symtab;
|
||||
import com.sun.tools.javac.code.Type;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -48,9 +48,9 @@ import java.util.stream.Stream;
|
||||
@BugPattern(
|
||||
name = "LexicographicalAnnotationAttributeListing",
|
||||
summary = "Where possible, sort annotation array attributes lexicographically",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.STYLE)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = STYLE)
|
||||
public final class LexicographicalAnnotationAttributeListingCheck extends BugChecker
|
||||
implements AnnotationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@@ -153,7 +153,7 @@ public final class LexicographicalAnnotationAttributeListingCheck extends BugChe
|
||||
// XXX: Perhaps we should use `Collator` with `.setStrength(Collator.PRIMARY)` and
|
||||
// `getCollationKey`. Not clear whether that's worth the hassle at this point.
|
||||
return ImmutableList.sortedCopyOf(
|
||||
Comparator.comparing(
|
||||
comparing(
|
||||
e -> getStructure(e, state),
|
||||
Comparators.lexicographical(
|
||||
Comparators.lexicographical(
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
|
||||
import static java.util.Comparator.comparing;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
|
||||
import com.google.errorprone.fixes.Fix;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.sun.source.tree.AnnotationTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} that flags annotations that are not lexicographically sorted.
|
||||
*
|
||||
* <p>The idea behind this checker is that maintaining a sorted sequence simplifies conflict
|
||||
* resolution, and can even avoid it if two branches add the same annotation.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "LexicographicalAnnotationListing",
|
||||
summary = "Sort annotations lexicographically where possible",
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = STYLE)
|
||||
public final class LexicographicalAnnotationListingCheck extends BugChecker
|
||||
implements MethodTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public Description matchMethod(MethodTree tree, VisitorState state) {
|
||||
List<? extends AnnotationTree> originalOrdering = tree.getModifiers().getAnnotations();
|
||||
if (originalOrdering.size() < 2) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
ImmutableList<? extends AnnotationTree> sortedAnnotations = sort(originalOrdering, state);
|
||||
if (originalOrdering.equals(sortedAnnotations)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
Optional<Fix> fix = tryFixOrdering(originalOrdering, sortedAnnotations, state);
|
||||
|
||||
Description.Builder description = buildDescription(tree);
|
||||
fix.ifPresent(description::addFix);
|
||||
return description.build();
|
||||
}
|
||||
|
||||
private static ImmutableList<? extends AnnotationTree> sort(
|
||||
List<? extends AnnotationTree> annotations, VisitorState state) {
|
||||
return annotations.stream()
|
||||
.sorted(comparing(annotation -> Util.treeToString(annotation, state)))
|
||||
.collect(toImmutableList());
|
||||
}
|
||||
|
||||
private static Optional<Fix> tryFixOrdering(
|
||||
List<? extends AnnotationTree> originalAnnotations,
|
||||
ImmutableList<? extends AnnotationTree> sortedAnnotations,
|
||||
VisitorState state) {
|
||||
return Streams.zip(
|
||||
originalAnnotations.stream(),
|
||||
sortedAnnotations.stream(),
|
||||
(original, replacement) ->
|
||||
SuggestedFix.builder().replace(original, Util.treeToString(replacement, state)))
|
||||
.reduce(SuggestedFix.Builder::merge)
|
||||
.map(SuggestedFix.Builder::build);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.STYLE;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.base.VerifyException;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher;
|
||||
@@ -47,13 +47,15 @@ import javax.lang.model.element.Name;
|
||||
// black-and-white. Maybe we can more closely approximate it?
|
||||
// XXX: With Java 9's introduction of `Predicate.not`, we could write many lambda expressions to
|
||||
// `not(some::reference)`.
|
||||
// XXX: This check is extremely inefficient due to its reliance on `SuggestedFixes.compilesWithFix`.
|
||||
// Palantir's `LambdaMethodReference` check seems to suffer a similar issue at this time.
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "MethodReferenceUsage",
|
||||
summary = "Prefer method references over lambda expressions",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.STYLE)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = STYLE)
|
||||
public final class MethodReferenceUsageCheck extends BugChecker
|
||||
implements LambdaExpressionTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@@ -67,7 +69,10 @@ public final class MethodReferenceUsageCheck extends BugChecker
|
||||
*/
|
||||
return constructMethodRef(tree, tree.getBody())
|
||||
.map(SuggestedFix.Builder::build)
|
||||
.filter(fix -> SuggestedFixes.compilesWithFix(fix, state))
|
||||
.filter(
|
||||
fix ->
|
||||
SuggestedFixes.compilesWithFix(
|
||||
fix, state, ImmutableList.of(), /* onlyInSameCompilationUnit= */ true))
|
||||
.map(fix -> describeMatch(tree, fix))
|
||||
.orElse(Description.NO_MATCH);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
@@ -7,14 +10,12 @@ import static com.google.errorprone.matchers.Matchers.isType;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.MultiMatcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.AnnotationTree;
|
||||
import com.sun.source.tree.ClassTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
@@ -25,12 +26,12 @@ import com.sun.source.tree.Tree;
|
||||
@BugPattern(
|
||||
name = "MissingRefasterAnnotation",
|
||||
summary = "The Refaster template contains a method without any Refaster annotations",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.WARNING,
|
||||
tags = StandardTags.LIKELY_ERROR)
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class MissingRefasterAnnotationCheck extends BugChecker implements ClassTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final MultiMatcher<Tree, AnnotationTree> HAS_REFASTER_ANNOTATION =
|
||||
private static final MultiMatcher<Tree, AnnotationTree> REFASTER_ANNOTATION =
|
||||
annotations(
|
||||
AT_LEAST_ONE,
|
||||
anyOf(
|
||||
@@ -44,7 +45,8 @@ public final class MissingRefasterAnnotationCheck extends BugChecker implements
|
||||
tree.getMembers().stream()
|
||||
.filter(member -> member.getKind() == Tree.Kind.METHOD)
|
||||
.map(MethodTree.class::cast)
|
||||
.map(method -> HAS_REFASTER_ANNOTATION.matches(method, state))
|
||||
.filter(method -> !ASTHelpers.isGeneratedConstructor(method))
|
||||
.map(method -> REFASTER_ANNOTATION.matches(method, state))
|
||||
.distinct()
|
||||
.count();
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.Matchers.staticMethod;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags method invocations for which all arguments are wrapped using
|
||||
* {@link org.mockito.Mockito#eq}; this is redundant.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "MockitoStubbing",
|
||||
summary = "Don't unnecessarily use Mockito's `eq(...)`",
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class MockitoStubbingCheck extends BugChecker implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<ExpressionTree> MOCKITO_EQ_METHOD =
|
||||
staticMethod().onClass("org.mockito.ArgumentMatchers").named("eq");
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
List<? extends ExpressionTree> arguments = tree.getArguments();
|
||||
if (arguments.isEmpty() || !arguments.stream().allMatch(arg -> isEqInvocation(arg, state))) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
|
||||
for (ExpressionTree arg : arguments) {
|
||||
suggestedFix.replace(
|
||||
arg,
|
||||
Util.treeToString(
|
||||
Iterables.getOnlyElement(((MethodInvocationTree) arg).getArguments()), state));
|
||||
}
|
||||
|
||||
return describeMatch(tree, suggestedFix.build());
|
||||
}
|
||||
|
||||
private static boolean isEqInvocation(ExpressionTree tree, VisitorState state) {
|
||||
return tree instanceof MethodInvocationTree && MOCKITO_EQ_METHOD.matches(tree, state);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.PERFORMANCE;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
|
||||
import static java.util.function.Predicate.not;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.base.VerifyException;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
@@ -30,6 +31,7 @@ import com.sun.tools.javac.tree.JCTree.JCMemberReference;
|
||||
import java.util.Comparator;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags {@code Comparator#comparing*} invocations that can be replaced
|
||||
@@ -37,16 +39,15 @@ import java.util.function.Function;
|
||||
*/
|
||||
// XXX: Add more documentation. Explain how this is useful in the face of refactoring to more
|
||||
// specific types.
|
||||
// XXX: Change this checker's name?
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "PrimitiveComparison",
|
||||
summary =
|
||||
"Ensure invocations of `Comparator#comparing{,Double,Int,Long}` match the return type"
|
||||
+ " of the provided function",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.WARNING,
|
||||
tags = StandardTags.PERFORMANCE)
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = PERFORMANCE)
|
||||
public final class PrimitiveComparisonCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@@ -77,23 +78,53 @@ public final class PrimitiveComparisonCheck extends BugChecker
|
||||
}
|
||||
|
||||
return getPotentiallyBoxedReturnType(tree.getArguments().get(0))
|
||||
.flatMap(cmpType -> tryFix(tree, state, cmpType, isStatic))
|
||||
.flatMap(cmpType -> attemptMethodInvocationReplacement(tree, cmpType, isStatic, state))
|
||||
.map(fix -> describeMatch(tree, fix))
|
||||
.orElse(Description.NO_MATCH);
|
||||
}
|
||||
|
||||
private static Optional<Fix> tryFix(
|
||||
MethodInvocationTree tree, VisitorState state, Type cmpType, boolean isStatic) {
|
||||
private static Optional<Fix> attemptMethodInvocationReplacement(
|
||||
MethodInvocationTree tree, Type cmpType, boolean isStatic, VisitorState state) {
|
||||
return Optional.ofNullable(ASTHelpers.getSymbol(tree))
|
||||
.map(methodSymbol -> methodSymbol.getSimpleName().toString())
|
||||
.flatMap(
|
||||
actualMethodName ->
|
||||
Optional.of(getPreferredMethod(state, cmpType, isStatic))
|
||||
Optional.of(getPreferredMethod(cmpType, isStatic, state))
|
||||
.filter(not(actualMethodName::equals)))
|
||||
.map(
|
||||
preferredMethodName ->
|
||||
prefixTypeArgumentsIfRelevant(preferredMethodName, tree, cmpType, state))
|
||||
.map(preferredMethodName -> suggestFix(tree, preferredMethodName, state));
|
||||
}
|
||||
|
||||
private static String getPreferredMethod(VisitorState state, Type cmpType, boolean isStatic) {
|
||||
/**
|
||||
* Prefixes the given method name with generic type parameters if it replaces a {@code
|
||||
* Comparator#comparing{,Double,Long,Int}} method which also has generic type parameters.
|
||||
*
|
||||
* <p>Such type parameters are retained as they are likely required.
|
||||
*
|
||||
* <p>Note that any type parameter to {@code Comparator#thenComparing} is likely redundant, and in
|
||||
* any case becomes obsolete once that method is replaced with {@code
|
||||
* Comparator#thenComparing{Double,Long,Int}}. Conversion in the opposite direction does not
|
||||
* require the introduction of a generic type parameter.
|
||||
*/
|
||||
private static String prefixTypeArgumentsIfRelevant(
|
||||
String preferredMethodName, MethodInvocationTree tree, Type cmpType, VisitorState state) {
|
||||
if (tree.getTypeArguments().isEmpty() || preferredMethodName.startsWith("then")) {
|
||||
return preferredMethodName;
|
||||
}
|
||||
|
||||
String typeArguments =
|
||||
Stream.concat(
|
||||
Stream.of(Util.treeToString(tree.getTypeArguments().get(0), state)),
|
||||
Stream.of(cmpType.tsym.getSimpleName())
|
||||
.filter(u -> "comparing".equals(preferredMethodName)))
|
||||
.collect(joining(", ", "<", ">"));
|
||||
|
||||
return typeArguments + preferredMethodName;
|
||||
}
|
||||
|
||||
private static String getPreferredMethod(Type cmpType, boolean isStatic, VisitorState state) {
|
||||
Types types = state.getTypes();
|
||||
Symtab symtab = state.getSymtab();
|
||||
|
||||
@@ -128,9 +159,6 @@ public final class PrimitiveComparisonCheck extends BugChecker
|
||||
}
|
||||
}
|
||||
|
||||
// XXX: We drop explicitly specified generic type information. In case the number of type
|
||||
// arguments before and after doesn't match, that's for the better. But if we e.g. replace
|
||||
// `comparingLong` with `comparingInt`, then we should retain it.
|
||||
private static Fix suggestFix(
|
||||
MethodInvocationTree tree, String preferredMethodName, VisitorState state) {
|
||||
ExpressionTree expr = tree.getMethodSelect();
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.Matchers.allOf;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.isNonNull;
|
||||
import static com.google.errorprone.matchers.Matchers.isNonNullUsingDataflow;
|
||||
import static com.google.errorprone.matchers.Matchers.isSameType;
|
||||
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
|
||||
import static com.google.errorprone.matchers.Matchers.not;
|
||||
@@ -12,9 +15,6 @@ import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.ErrorProneFlags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
@@ -47,9 +47,9 @@ import java.util.Optional;
|
||||
@BugPattern(
|
||||
name = "RedundantStringConversion",
|
||||
summary = "Avoid redundant string conversions when possible",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class RedundantStringConversionCheck extends BugChecker
|
||||
implements BinaryTreeMatcher, CompoundAssignmentTreeMatcher, MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@@ -64,7 +64,8 @@ public final class RedundantStringConversionCheck extends BugChecker
|
||||
private static final Matcher<ExpressionTree> MARKER = isSubtypeOf("org.slf4j.Marker");
|
||||
private static final Matcher<ExpressionTree> STRING = isSameType(String.class);
|
||||
private static final Matcher<ExpressionTree> THROWABLE = isSubtypeOf(Throwable.class);
|
||||
private static final Matcher<ExpressionTree> NON_NULL_STRING = allOf(STRING, isNonNull());
|
||||
private static final Matcher<ExpressionTree> NON_NULL_STRING =
|
||||
allOf(STRING, isNonNullUsingDataflow());
|
||||
private static final Matcher<ExpressionTree> NOT_FORMATTABLE =
|
||||
not(isSubtypeOf(Formattable.class));
|
||||
private static final Matcher<ExpressionTree> WELL_KNOWN_STRING_CONVERSION_METHODS =
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags unnecessary {@link Refaster#anyOf(Object[])} usages.
|
||||
*
|
||||
* <p>Note that this logic can't be implemented as a Refaster template, as the {@link Refaster}
|
||||
* class is treated specially.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "RefasterAnyOfUsage",
|
||||
summary = "`Refaster#anyOf` should be passed at least two parameters",
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class RefasterAnyOfUsageCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<ExpressionTree> REFASTER_ANY_OF =
|
||||
staticMethod().onClass(Refaster.class.getName()).named("anyOf");
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
if (REFASTER_ANY_OF.matches(tree, state)) {
|
||||
switch (tree.getArguments().size()) {
|
||||
case 0:
|
||||
// We can't safely fix this case; dropping the expression may produce non-compilable code.
|
||||
return describeMatch(tree);
|
||||
case 1:
|
||||
return describeMatch(
|
||||
tree,
|
||||
SuggestedFix.replace(tree, Util.treeToString(tree.getArguments().get(0), state)));
|
||||
default:
|
||||
/* Handled below. */
|
||||
}
|
||||
}
|
||||
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,14 @@ package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.common.collect.ImmutableRangeSet.toImmutableRangeSet;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static java.util.function.Predicate.not;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Suppliers;
|
||||
import com.google.common.collect.ImmutableCollection;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
@@ -17,9 +21,6 @@ import com.google.common.collect.TreeRangeSet;
|
||||
import com.google.common.reflect.ClassPath;
|
||||
import com.google.common.reflect.ClassPath.ResourceInfo;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.CodeTransformer;
|
||||
import com.google.errorprone.CompositeCodeTransformer;
|
||||
import com.google.errorprone.ErrorProneFlags;
|
||||
@@ -30,6 +31,7 @@ import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
|
||||
import com.google.errorprone.fixes.Replacement;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.sun.source.tree.CompilationUnitTree;
|
||||
import com.sun.source.util.TreePath;
|
||||
import com.sun.tools.javac.tree.EndPosTable;
|
||||
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
|
||||
import java.io.IOException;
|
||||
@@ -41,10 +43,13 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import javax.naming.Context;
|
||||
import tech.picnic.errorprone.plexus.compiler.javac.caching.CachingJavacCompiler;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags code which can be simplified using Refaster templates located on
|
||||
@@ -58,15 +63,20 @@ import java.util.stream.Stream;
|
||||
@BugPattern(
|
||||
name = "Refaster",
|
||||
summary = "Write idiomatic code when possible",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class RefasterCheck extends BugChecker implements CompilationUnitTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String REFASTER_TEMPLATE_SUFFIX = ".refaster";
|
||||
private static final String INCLUDED_TEMPLATES_PATTERN_FLAG = "Refaster:NamePattern";
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final CodeTransformer codeTransformer;
|
||||
@VisibleForTesting
|
||||
static final Supplier<ImmutableListMultimap<String, CodeTransformer>> ALL_CODE_TRANSFORMERS =
|
||||
Suppliers.memoize(RefasterCheck::loadAllCodeTransformers);
|
||||
|
||||
private final ErrorProneFlags errorProneFlags;
|
||||
private final Supplier<CodeTransformer> codeTransformer;
|
||||
|
||||
/** Instantiates the default {@link RefasterCheck}. */
|
||||
public RefasterCheck() {
|
||||
@@ -79,20 +89,45 @@ public final class RefasterCheck extends BugChecker implements CompilationUnitTr
|
||||
* @param flags Any provided command line flags.
|
||||
*/
|
||||
public RefasterCheck(ErrorProneFlags flags) {
|
||||
codeTransformer = createCompositeCodeTransformer(flags, loadAllCodeTransformers());
|
||||
errorProneFlags = flags;
|
||||
codeTransformer = Suppliers.memoize(() -> createCompositeCodeTransformer(flags));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
RefasterCheck(
|
||||
ErrorProneFlags flags, ImmutableListMultimap<String, CodeTransformer> allTransformers) {
|
||||
codeTransformer = createCompositeCodeTransformer(flags, allTransformers);
|
||||
}
|
||||
// XXX: Need to somehow convert `Description` to handle classloading issue.
|
||||
// private BiFunction<TreePath, Context, List<Description>>
|
||||
|
||||
@Override
|
||||
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
|
||||
// XXX Use the `codeTransformer` field only if `cache` is empty. In that case, populate the
|
||||
// cache.
|
||||
// XXX: Current code is wrong: doesn't respect flags.
|
||||
System.out.println("XXXX :" + CachingJavacCompiler.class.toString());
|
||||
System.out.println("XXXX Path :" + TreePath.class.hashCode());
|
||||
System.out.println("XXXX Context:" + Context.class.hashCode());
|
||||
ConcurrentMap<String, Object> cache = state.context.get(ConcurrentMap.class);
|
||||
System.err.printf("XXX %s%n", cache);
|
||||
CodeTransformer transformer;
|
||||
if (cache != null) {
|
||||
cache.compute("x", (a, b) -> b instanceof Integer ? ((Integer) b) + 1 : 1);
|
||||
transformer = (CodeTransformer) cache.computeIfAbsent("c", k -> codeTransformer.get());
|
||||
} else {
|
||||
// We're not using the hacked compiler
|
||||
System.err.printf("XXX NOP!%n");
|
||||
transformer = codeTransformer.get();
|
||||
}
|
||||
|
||||
/* First, collect all matches. */
|
||||
List<Description> matches = new ArrayList<>();
|
||||
codeTransformer.apply(state.getPath(), new SubContext(state.context), matches::add);
|
||||
try {
|
||||
transformer.apply(state.getPath(), new SubContext(state.context), matches::add);
|
||||
} catch (LinkageError e) {
|
||||
// XXX: This `try/catch` block handles the issue described and resolved in
|
||||
// https://github.com/google/error-prone/pull/2456. Drop this block once that change is
|
||||
// released.
|
||||
// XXX: Find a way to identify that we're running Picnic's Error Prone fork and disable this
|
||||
// fallback if so, as it might hide other bugs.
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
/* Then apply them. */
|
||||
applyMatches(matches, ((JCCompilationUnit) tree).endPositions, state);
|
||||
|
||||
@@ -152,8 +187,8 @@ public final class RefasterCheck extends BugChecker implements CompilationUnitTr
|
||||
return description.fixes.stream().flatMap(fix -> fix.getReplacements(endPositions).stream());
|
||||
}
|
||||
|
||||
private static CodeTransformer createCompositeCodeTransformer(
|
||||
ErrorProneFlags flags, ImmutableListMultimap<String, CodeTransformer> allTransformers) {
|
||||
private static CodeTransformer createCompositeCodeTransformer(ErrorProneFlags flags) {
|
||||
ImmutableListMultimap<String, CodeTransformer> allTransformers = ALL_CODE_TRANSFORMERS.get();
|
||||
return CompositeCodeTransformer.compose(
|
||||
flags
|
||||
.get(INCLUDED_TEMPLATES_PATTERN_FLAG)
|
||||
@@ -170,8 +205,7 @@ public final class RefasterCheck extends BugChecker implements CompilationUnitTr
|
||||
.collect(toImmutableList());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static ImmutableListMultimap<String, CodeTransformer> loadAllCodeTransformers() {
|
||||
private static ImmutableListMultimap<String, CodeTransformer> loadAllCodeTransformers() {
|
||||
ImmutableListMultimap.Builder<String, CodeTransformer> transformers =
|
||||
ImmutableListMultimap.builder();
|
||||
|
||||
@@ -188,10 +222,7 @@ public final class RefasterCheck extends BugChecker implements CompilationUnitTr
|
||||
|
||||
private static ImmutableSet<ResourceInfo> getClassPathResources() {
|
||||
try {
|
||||
return ClassPath.from(
|
||||
Objects.requireNonNullElseGet(
|
||||
RefasterCheck.class.getClassLoader(), () -> ClassLoader.getSystemClassLoader()))
|
||||
.getResources();
|
||||
return ClassPath.from(ClassLoader.getSystemClassLoader()).getResources();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to scan classpath for resources", e);
|
||||
}
|
||||
@@ -212,7 +243,9 @@ public final class RefasterCheck extends BugChecker implements CompilationUnitTr
|
||||
private static Optional<CodeTransformer> loadCodeTransformer(ResourceInfo resource) {
|
||||
try (InputStream in = resource.url().openStream();
|
||||
ObjectInputStream ois = new ObjectInputStream(in)) {
|
||||
return Optional.of((CodeTransformer) ois.readObject());
|
||||
@SuppressWarnings("BanSerializableRead" /* Part of the Refaster API. */)
|
||||
CodeTransformer codeTransformer = (CodeTransformer) ois.readObject();
|
||||
return Optional.of(codeTransformer);
|
||||
} catch (NoSuchElementException e) {
|
||||
/* For some reason we can't load the resource. Skip it. */
|
||||
// XXX: Should we log this?
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.ALL;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.isSameType;
|
||||
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
|
||||
import static com.google.errorprone.matchers.Matchers.not;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.ProvidesFix;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
|
||||
@@ -34,10 +32,9 @@ import com.sun.source.tree.Tree;
|
||||
@BugPattern(
|
||||
name = "RequestMappingAnnotation",
|
||||
summary = "Make sure all `@RequestMapping` method parameters are annotated",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.WARNING,
|
||||
tags = StandardTags.LIKELY_ERROR,
|
||||
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class RequestMappingAnnotationCheck extends BugChecker implements MethodTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String ANN_PACKAGE_PREFIX = "org.springframework.web.bind.annotation.";
|
||||
@@ -53,8 +50,11 @@ public final class RequestMappingAnnotationCheck extends BugChecker implements M
|
||||
isType(ANN_PACKAGE_PREFIX + "PostMapping"),
|
||||
isType(ANN_PACKAGE_PREFIX + "PutMapping"),
|
||||
isType(ANN_PACKAGE_PREFIX + "RequestMapping")));
|
||||
// XXX: Add other parameters as necessary. See
|
||||
// https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments.
|
||||
// XXX: Add other parameters as necessary. Also consider whether it makes sense to have WebMVC-
|
||||
// and WebFlux-specific logic. See
|
||||
// https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-arguments
|
||||
// and
|
||||
// https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-arguments.
|
||||
private static final Matcher<MethodTree> LACKS_PARAMETER_ANNOTATION =
|
||||
not(
|
||||
methodHasParameters(
|
||||
@@ -68,10 +68,17 @@ public final class RequestMappingAnnotationCheck extends BugChecker implements M
|
||||
isType(ANN_PACKAGE_PREFIX + "RequestHeader"),
|
||||
isType(ANN_PACKAGE_PREFIX + "RequestParam"))),
|
||||
isSameType("java.io.InputStream"),
|
||||
isSameType("java.time.ZoneId"),
|
||||
isSameType("java.util.Locale"),
|
||||
isSameType("java.util.TimeZone"),
|
||||
isSameType("javax.servlet.http.HttpServletRequest"),
|
||||
isSameType("javax.servlet.http.HttpServletResponse"),
|
||||
isSameType("org.springframework.http.HttpMethod"),
|
||||
isSubtypeOf("org.springframework.web.context.request.WebRequest"))));
|
||||
isSameType("org.springframework.web.context.request.NativeWebRequest"),
|
||||
isSameType("org.springframework.web.context.request.WebRequest"),
|
||||
isSameType("org.springframework.web.server.ServerWebExchange"),
|
||||
isSameType("org.springframework.web.util.UriBuilder"),
|
||||
isSameType("org.springframework.web.util.UriComponentsBuilder"))));
|
||||
|
||||
@Override
|
||||
public Description matchMethod(MethodTree tree, VisitorState state) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.allOf;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableCollection;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.sun.source.tree.VariableTree;
|
||||
|
||||
/** A {@link BugChecker} which flags {@code @RequestParam} parameters with an unsupported type. */
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "RequestParamType",
|
||||
summary = "`@RequestParam` does not support `ImmutableCollection` and `ImmutableMap` subtypes",
|
||||
linkType = NONE,
|
||||
severity = ERROR,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class RequestParamTypeCheck extends BugChecker implements VariableTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<VariableTree> HAS_UNSUPPORTED_REQUEST_PARAM =
|
||||
allOf(
|
||||
annotations(AT_LEAST_ONE, isType("org.springframework.web.bind.annotation.RequestParam")),
|
||||
anyOf(isSubtypeOf(ImmutableCollection.class), isSubtypeOf(ImmutableMap.class)));
|
||||
|
||||
@Override
|
||||
public Description matchVariable(VariableTree tree, VisitorState state) {
|
||||
return HAS_UNSUPPORTED_REQUEST_PARAM.matches(tree, state)
|
||||
? describeMatch(tree)
|
||||
: Description.NO_MATCH;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
|
||||
import static com.google.errorprone.matchers.Matchers.annotations;
|
||||
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
|
||||
import static com.google.errorprone.matchers.Matchers.isType;
|
||||
|
||||
import com.google.auto.common.AnnotationMirrors;
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.fixes.SuggestedFixes;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.google.errorprone.matchers.MultiMatcher;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.AnnotationTree;
|
||||
import com.sun.source.tree.MethodTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
|
||||
/**
|
||||
* A {@link BugChecker} which flags methods with Spring's {@code @Scheduled} annotation that lack
|
||||
* New Relic Agent's {@code @Trace(dispatcher = true)}.
|
||||
*/
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "ScheduledTransactionTrace",
|
||||
summary = "Scheduled operation must start a new New Relic transaction",
|
||||
linkType = NONE,
|
||||
severity = ERROR,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class ScheduledTransactionTraceCheck extends BugChecker implements MethodTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String TRACE_ANNOTATION_FQCN = "com.newrelic.api.agent.Trace";
|
||||
private static final Matcher<Tree> IS_SCHEDULED =
|
||||
hasAnnotation("org.springframework.scheduling.annotation.Scheduled");
|
||||
private static final MultiMatcher<Tree, AnnotationTree> TRACE_ANNOTATION =
|
||||
annotations(AT_LEAST_ONE, isType(TRACE_ANNOTATION_FQCN));
|
||||
|
||||
@Override
|
||||
public Description matchMethod(MethodTree tree, VisitorState state) {
|
||||
if (!IS_SCHEDULED.matches(tree, state)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
ImmutableList<AnnotationTree> traceAnnotations =
|
||||
TRACE_ANNOTATION.multiMatchResult(tree, state).matchingNodes();
|
||||
if (traceAnnotations.isEmpty()) {
|
||||
/* This method completely lacks the `@Trace` annotation; add it. */
|
||||
return describeMatch(
|
||||
tree,
|
||||
SuggestedFix.builder()
|
||||
.addImport(TRACE_ANNOTATION_FQCN)
|
||||
.prefixWith(tree, "@Trace(dispatcher = true)")
|
||||
.build());
|
||||
}
|
||||
|
||||
AnnotationTree traceAnnotation = Iterables.getOnlyElement(traceAnnotations);
|
||||
if (isCorrectAnnotation(traceAnnotation)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
/*
|
||||
* The `@Trace` annotation is present but does not specify `dispatcher = true`. Add or update
|
||||
* the `dispatcher` annotation element.
|
||||
*/
|
||||
return describeMatch(
|
||||
traceAnnotation,
|
||||
SuggestedFixes.updateAnnotationArgumentValues(
|
||||
traceAnnotation, "dispatcher", ImmutableList.of("true"))
|
||||
.build());
|
||||
}
|
||||
|
||||
private static boolean isCorrectAnnotation(AnnotationTree traceAnnotation) {
|
||||
return Boolean.TRUE.equals(
|
||||
AnnotationMirrors.getAnnotationValue(
|
||||
ASTHelpers.getAnnotationMirror(traceAnnotation), "dispatcher")
|
||||
.getValue());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.base.Verify.verify;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR;
|
||||
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
|
||||
import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
@@ -33,9 +33,9 @@ import java.util.Optional;
|
||||
@BugPattern(
|
||||
name = "Slf4jLogStatement",
|
||||
summary = "Make sure SLF4J log statements contain proper placeholders with matching arguments",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.WARNING,
|
||||
tags = StandardTags.LIKELY_ERROR)
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = LIKELY_ERROR)
|
||||
public final class Slf4jLogStatementCheck extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.base.Verify.verify;
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static java.util.function.Predicate.not;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
@@ -9,9 +12,6 @@ import com.google.common.base.VerifyException;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
|
||||
@@ -35,9 +35,9 @@ import java.util.Optional;
|
||||
name = "SpringMvcAnnotation",
|
||||
summary =
|
||||
"Prefer the conciseness of `@{Get,Put,Post,Delete,Patch}Mapping` over `@RequestMapping`",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class SpringMvcAnnotationCheck extends BugChecker implements AnnotationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final String ANN_PACKAGE_PREFIX = "org.springframework.web.bind.annotation.";
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.SIMPLIFICATION;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSetMultimap;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.LinkType;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.BugPattern.StandardTags;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher;
|
||||
@@ -17,15 +19,18 @@ import com.google.errorprone.fixes.Fix;
|
||||
import com.google.errorprone.fixes.SuggestedFix;
|
||||
import com.google.errorprone.fixes.SuggestedFixes;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.util.ASTHelpers;
|
||||
import com.sun.source.tree.MemberSelectTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import com.sun.source.tree.Tree;
|
||||
import java.util.Objects;
|
||||
import com.sun.tools.javac.code.Type;
|
||||
import java.util.Optional;
|
||||
|
||||
/** A {@link BugChecker} which flags methods that can and should be statically imported. */
|
||||
/**
|
||||
* A {@link BugChecker} which flags methods and constants that can and should be statically
|
||||
* imported.
|
||||
*/
|
||||
// XXX: Tricky cases:
|
||||
// - `org.springframework.http.MediaType` (do except for `ALL`?)
|
||||
// - `org.springframework.http.HttpStatus` (not always an improvement, and `valueOf` must
|
||||
// certainly be excluded)
|
||||
// - `com.google.common.collect.Tables`
|
||||
@@ -41,20 +46,28 @@ import java.util.Optional;
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "StaticImport",
|
||||
summary = "Method should be statically imported",
|
||||
linkType = LinkType.NONE,
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
tags = StandardTags.SIMPLIFICATION)
|
||||
summary = "Identifier should be statically imported",
|
||||
linkType = NONE,
|
||||
severity = SUGGESTION,
|
||||
tags = SIMPLIFICATION)
|
||||
public final class StaticImportCheck extends BugChecker implements MemberSelectTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Types whose members should be statically imported, unless exempted by {@link
|
||||
* #STATIC_IMPORT_EXEMPTED_MEMBERS} or {@link #STATIC_IMPORT_EXEMPTED_IDENTIFIERS}.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static final ImmutableSet<String> STATIC_IMPORT_CANDIDATE_CLASSES =
|
||||
static final ImmutableSet<String> STATIC_IMPORT_CANDIDATE_TYPES =
|
||||
ImmutableSet.of(
|
||||
"com.google.common.base.Preconditions",
|
||||
"com.google.common.base.Predicates",
|
||||
"com.google.common.base.Verify",
|
||||
"com.google.common.collect.MoreCollectors",
|
||||
"com.google.errorprone.BugPattern.LinkType",
|
||||
"com.google.errorprone.BugPattern.SeverityLevel",
|
||||
"com.google.errorprone.BugPattern.StandardTags",
|
||||
"com.google.errorprone.refaster.ImportPolicy",
|
||||
"com.mongodb.client.model.Accumulators",
|
||||
"com.mongodb.client.model.Aggregates",
|
||||
"com.mongodb.client.model.Filters",
|
||||
@@ -63,8 +76,10 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
"com.mongodb.client.model.Sorts",
|
||||
"com.mongodb.client.model.Updates",
|
||||
"java.nio.charset.StandardCharsets",
|
||||
"java.util.Collections",
|
||||
"java.util.Comparator",
|
||||
"java.util.Map.Entry",
|
||||
"java.util.regex.Pattern",
|
||||
"java.util.stream.Collectors",
|
||||
"org.assertj.core.api.Assertions",
|
||||
"org.assertj.core.api.InstanceOfAssertFactories",
|
||||
@@ -79,14 +94,17 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
"org.mockito.Answers",
|
||||
"org.mockito.ArgumentMatchers",
|
||||
"org.mockito.Mockito",
|
||||
"org.springframework.boot.test.context.SpringBootTest.WebEnvironment",
|
||||
"org.springframework.format.annotation.DateTimeFormat.ISO",
|
||||
"org.springframework.http.HttpHeaders",
|
||||
"org.springframework.http.HttpMethod",
|
||||
"org.springframework.http.MediaType",
|
||||
"org.testng.Assert",
|
||||
"reactor.function.TupleUtils");
|
||||
|
||||
/** Type members that should be statically imported. */
|
||||
@VisibleForTesting
|
||||
static final ImmutableSetMultimap<String, String> STATIC_IMPORT_CANDIDATE_METHODS =
|
||||
static final ImmutableSetMultimap<String, String> STATIC_IMPORT_CANDIDATE_MEMBERS =
|
||||
ImmutableSetMultimap.<String, String>builder()
|
||||
.putAll(
|
||||
"com.google.common.collect.ImmutableListMultimap",
|
||||
@@ -107,8 +125,10 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
.put("com.google.common.collect.ImmutableTable", "toImmutableTable")
|
||||
.put("com.google.common.collect.Sets", "toImmutableEnumSet")
|
||||
.put("com.google.common.base.Functions", "identity")
|
||||
.put("java.time.ZoneOffset", "UTC")
|
||||
.put("java.util.function.Function", "identity")
|
||||
.put("java.util.function.Predicate", "not")
|
||||
.put("java.util.UUID", "randomUUID")
|
||||
.put("org.junit.jupiter.params.provider.Arguments", "arguments")
|
||||
.putAll(
|
||||
"java.util.Objects",
|
||||
@@ -121,9 +141,57 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
.putAll("com.google.common.collect.Comparators", "emptiesFirst", "emptiesLast")
|
||||
.build();
|
||||
|
||||
/**
|
||||
* Type members that should never be statically imported.
|
||||
*
|
||||
* <p>Identifiers listed by {@link #STATIC_IMPORT_EXEMPTED_IDENTIFIERS} should be omitted from
|
||||
* this collection.
|
||||
*/
|
||||
// XXX: Perhaps the set of exempted `java.util.Collections` methods is too strict. For now any
|
||||
// method name that could be considered "too vague" or could conceivably mean something else in a
|
||||
// specific context is left out.
|
||||
@VisibleForTesting
|
||||
static final ImmutableSetMultimap<String, String> STATIC_IMPORT_EXEMPTED_MEMBERS =
|
||||
ImmutableSetMultimap.<String, String>builder()
|
||||
.put("com.mongodb.client.model.Filters", "empty")
|
||||
.putAll(
|
||||
"java.util.Collections",
|
||||
"addAll",
|
||||
"copy",
|
||||
"fill",
|
||||
"list",
|
||||
"max",
|
||||
"min",
|
||||
"nCopies",
|
||||
"rotate",
|
||||
"sort",
|
||||
"swap")
|
||||
.putAll("java.util.regex.Pattern", "compile", "matches", "quote")
|
||||
.put("org.springframework.http.MediaType", "ALL")
|
||||
.build();
|
||||
|
||||
/**
|
||||
* Identifiers that should never be statically imported.
|
||||
*
|
||||
* <p>This should be a superset of the identifiers flagged by {@link
|
||||
* com.google.errorprone.bugpatterns.BadImport}.
|
||||
*/
|
||||
@VisibleForTesting
|
||||
static final ImmutableSet<String> STATIC_IMPORT_EXEMPTED_IDENTIFIERS =
|
||||
ImmutableSet.of(
|
||||
"builder",
|
||||
"create",
|
||||
"copyOf",
|
||||
"from",
|
||||
"getDefaultInstance",
|
||||
"INSTANCE",
|
||||
"newBuilder",
|
||||
"of",
|
||||
"valueOf");
|
||||
|
||||
@Override
|
||||
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
|
||||
if (!isCandidate(state)) {
|
||||
if (!isCandidateContext(state) || !isCandidate(tree)) {
|
||||
return Description.NO_MATCH;
|
||||
}
|
||||
|
||||
@@ -138,10 +206,9 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
.orElse(Description.NO_MATCH);
|
||||
}
|
||||
|
||||
private static boolean isCandidate(VisitorState state) {
|
||||
private static boolean isCandidateContext(VisitorState state) {
|
||||
Tree parentTree =
|
||||
Objects.requireNonNull(
|
||||
state.getPath().getParentPath(), "MemberSelectTree lacks enclosing node")
|
||||
requireNonNull(state.getPath().getParentPath(), "MemberSelectTree lacks enclosing node")
|
||||
.getLeaf();
|
||||
switch (parentTree.getKind()) {
|
||||
case IMPORT:
|
||||
@@ -154,6 +221,17 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCandidate(MemberSelectTree tree) {
|
||||
String identifier = tree.getIdentifier().toString();
|
||||
if (STATIC_IMPORT_EXEMPTED_IDENTIFIERS.contains(identifier)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Type type = ASTHelpers.getType(tree.getExpression());
|
||||
return type != null
|
||||
&& !STATIC_IMPORT_EXEMPTED_MEMBERS.containsEntry(type.toString(), identifier);
|
||||
}
|
||||
|
||||
private static Optional<String> getCandidateSimpleName(StaticImportInfo importInfo) {
|
||||
String canonicalName = importInfo.canonicalName();
|
||||
return importInfo
|
||||
@@ -161,8 +239,8 @@ public final class StaticImportCheck extends BugChecker implements MemberSelectT
|
||||
.toJavaUtil()
|
||||
.filter(
|
||||
name ->
|
||||
STATIC_IMPORT_CANDIDATE_CLASSES.contains(canonicalName)
|
||||
|| STATIC_IMPORT_CANDIDATE_METHODS.containsEntry(canonicalName, name));
|
||||
STATIC_IMPORT_CANDIDATE_TYPES.contains(canonicalName)
|
||||
|| STATIC_IMPORT_CANDIDATE_MEMBERS.containsEntry(canonicalName, name));
|
||||
}
|
||||
|
||||
private static Optional<Fix> tryStaticImport(
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.LinkType.NONE;
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
|
||||
import static com.google.errorprone.BugPattern.StandardTags.FRAGILE_CODE;
|
||||
import static com.google.errorprone.matchers.Matchers.allOf;
|
||||
import static com.google.errorprone.matchers.Matchers.anyOf;
|
||||
import static com.google.errorprone.matchers.Matchers.enclosingClass;
|
||||
import static com.google.errorprone.matchers.Matchers.instanceMethod;
|
||||
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
|
||||
import static com.google.errorprone.matchers.Matchers.not;
|
||||
import static com.google.errorprone.matchers.Matchers.staticMethod;
|
||||
|
||||
import com.google.auto.service.AutoService;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
|
||||
import com.google.errorprone.matchers.Description;
|
||||
import com.google.errorprone.matchers.Matcher;
|
||||
import com.sun.source.tree.ExpressionTree;
|
||||
import com.sun.source.tree.MethodInvocationTree;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
|
||||
/** A {@link BugChecker} which flags illegal time-zone related operations. */
|
||||
@AutoService(BugChecker.class)
|
||||
@BugPattern(
|
||||
name = "TimeZoneUsage",
|
||||
summary =
|
||||
"Derive the current time from an existing `Clock` Spring bean, and don't rely on a `Clock`'s time zone",
|
||||
linkType = NONE,
|
||||
severity = WARNING,
|
||||
tags = FRAGILE_CODE)
|
||||
public final class TimeZoneUsageCheck extends BugChecker implements MethodInvocationTreeMatcher {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final Matcher<ExpressionTree> BANNED_TIME_METHOD =
|
||||
anyOf(
|
||||
allOf(
|
||||
instanceMethod()
|
||||
.onDescendantOf(Clock.class.getName())
|
||||
.namedAnyOf("getZone", "withZone"),
|
||||
not(enclosingClass(isSubtypeOf(Clock.class)))),
|
||||
staticMethod()
|
||||
.onClass(Clock.class.getName())
|
||||
.namedAnyOf(
|
||||
"system",
|
||||
"systemDefaultZone",
|
||||
"systemUTC",
|
||||
"tickMillis",
|
||||
"tickMinutes",
|
||||
"tickSeconds"),
|
||||
staticMethod()
|
||||
.onClassAny(
|
||||
LocalDate.class.getName(),
|
||||
LocalDateTime.class.getName(),
|
||||
LocalTime.class.getName())
|
||||
.named("now"),
|
||||
staticMethod().onClassAny(Instant.class.getName()).named("now").withParameters());
|
||||
|
||||
@Override
|
||||
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
|
||||
return BANNED_TIME_METHOD.matches(tree, state)
|
||||
? buildDescription(tree).build()
|
||||
: Description.NO_MATCH;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
/** Picnic Error Prone Contrib checks. */
|
||||
@CheckReturnValue
|
||||
@ParametersAreNonnullByDefault
|
||||
@com.google.errorprone.annotations.CheckReturnValue
|
||||
@javax.annotation.ParametersAreNonnullByDefault
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.annotations.CheckReturnValue;
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
|
||||
@@ -8,13 +8,22 @@ import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import java.math.BigDecimal;
|
||||
import org.assertj.core.api.AbstractBigDecimalAssert;
|
||||
import org.assertj.core.api.BigDecimalAssert;
|
||||
|
||||
// XXX: If we add a rule which drops unnecessary `L` suffixes from literal longs, then the `0L`/`1L`
|
||||
// cases below can go.
|
||||
/**
|
||||
* Refaster templates related to AssertJ assertions over {@link BigDecimal}s.
|
||||
*
|
||||
* <p>Note that, contrary to collections of Refaster templates for other {@link
|
||||
* org.assertj.core.api.NumberAssert} subtypes, these templates do not rewrite to/from {@link
|
||||
* BigDecimalAssert#isEqualTo(Object)} and {@link BigDecimalAssert#isNotEqualTo(Object)}. This is
|
||||
* because {@link BigDecimal#equals(Object)} considers not only the numeric value of compared
|
||||
* instances, but also their scale. As a result various seemingly straightforward transformations
|
||||
* would actually subtly change the assertion's semantics.
|
||||
*/
|
||||
final class AssertJBigDecimalTemplates {
|
||||
private AssertJBigDecimalTemplates() {}
|
||||
|
||||
static final class AbstractBigDecimalAssertIsEqualTo {
|
||||
static final class AbstractBigDecimalAssertIsEqualByComparingTo {
|
||||
@BeforeTemplate
|
||||
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
|
||||
return Refaster.anyOf(
|
||||
@@ -24,11 +33,11 @@ final class AssertJBigDecimalTemplates {
|
||||
|
||||
@AfterTemplate
|
||||
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
|
||||
return bigDecimalAssert.isEqualTo(n);
|
||||
return bigDecimalAssert.isEqualByComparingTo(n);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractBigDecimalAssertIsNotEqualTo {
|
||||
static final class AbstractBigDecimalAssertIsNotEqualByComparingTo {
|
||||
@BeforeTemplate
|
||||
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
|
||||
return Refaster.anyOf(
|
||||
@@ -38,52 +47,7 @@ final class AssertJBigDecimalTemplates {
|
||||
|
||||
@AfterTemplate
|
||||
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert, BigDecimal n) {
|
||||
return bigDecimalAssert.isNotEqualTo(n);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractBigDecimalAssertIsZero {
|
||||
@BeforeTemplate
|
||||
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return Refaster.anyOf(
|
||||
bigDecimalAssert.isZero(),
|
||||
bigDecimalAssert.isEqualTo(0L),
|
||||
bigDecimalAssert.isEqualTo(BigDecimal.ZERO));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return bigDecimalAssert.isEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractBigDecimalAssertIsNotZero {
|
||||
@BeforeTemplate
|
||||
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return Refaster.anyOf(
|
||||
bigDecimalAssert.isNotZero(),
|
||||
bigDecimalAssert.isNotEqualTo(0L),
|
||||
bigDecimalAssert.isNotEqualTo(BigDecimal.ZERO));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return bigDecimalAssert.isNotEqualTo(0);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractBigDecimalAssertIsOne {
|
||||
@BeforeTemplate
|
||||
AbstractBigDecimalAssert<?> before(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return Refaster.anyOf(
|
||||
bigDecimalAssert.isOne(),
|
||||
bigDecimalAssert.isEqualTo(1L),
|
||||
bigDecimalAssert.isEqualTo(BigDecimal.ONE));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractBigDecimalAssert<?> after(AbstractBigDecimalAssert<?> bigDecimalAssert) {
|
||||
return bigDecimalAssert.isEqualTo(1);
|
||||
return bigDecimalAssert.isNotEqualByComparingTo(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -59,7 +59,7 @@ final class AssertJBooleanTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractBooleanAssert<?> after(boolean b) {
|
||||
return assertThat(b).isTrue();
|
||||
}
|
||||
@@ -88,7 +88,7 @@ final class AssertJBooleanTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractBooleanAssert<?> after(boolean b) {
|
||||
return assertThat(b).isFalse();
|
||||
}
|
||||
|
||||
@@ -15,11 +15,7 @@ final class AssertJByteTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> byteAssert, byte n) {
|
||||
return Refaster.anyOf(
|
||||
byteAssert.isCloseTo(n, offset((byte) 0)),
|
||||
byteAssert.isCloseTo(Byte.valueOf(n), offset((byte) 0)),
|
||||
byteAssert.isCloseTo(n, withPercentage(0)),
|
||||
byteAssert.isCloseTo(Byte.valueOf(n), withPercentage(0)),
|
||||
byteAssert.isEqualTo(Byte.valueOf(n)));
|
||||
byteAssert.isCloseTo(n, offset((byte) 0)), byteAssert.isCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -33,10 +29,7 @@ final class AssertJByteTemplates {
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> byteAssert, byte n) {
|
||||
return Refaster.anyOf(
|
||||
byteAssert.isNotCloseTo(n, offset((byte) 0)),
|
||||
byteAssert.isNotCloseTo(Byte.valueOf(n), offset((byte) 0)),
|
||||
byteAssert.isNotCloseTo(n, withPercentage(0)),
|
||||
byteAssert.isNotCloseTo(Byte.valueOf(n), withPercentage(0)),
|
||||
byteAssert.isNotEqualTo(Byte.valueOf(n)));
|
||||
byteAssert.isNotCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -21,7 +21,7 @@ final class AssertJCharSequenceTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(CharSequence charSequence) {
|
||||
assertThat(charSequence).isEmpty();
|
||||
}
|
||||
@@ -36,7 +36,7 @@ final class AssertJCharSequenceTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractAssert<?, ?> after(CharSequence charSequence) {
|
||||
return assertThat(charSequence).isNotEmpty();
|
||||
}
|
||||
@@ -49,7 +49,7 @@ final class AssertJCharSequenceTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractAssert<?, ?> after(CharSequence charSequence, int length) {
|
||||
return assertThat(charSequence).hasSize(length);
|
||||
}
|
||||
|
||||
@@ -36,11 +36,7 @@ final class AssertJDoubleTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractDoubleAssert<?> before(AbstractDoubleAssert<?> doubleAssert, double n) {
|
||||
return Refaster.anyOf(
|
||||
doubleAssert.isCloseTo(n, offset(0.0)),
|
||||
doubleAssert.isCloseTo(Double.valueOf(n), offset(0.0)),
|
||||
doubleAssert.isCloseTo(n, withPercentage(0.0)),
|
||||
doubleAssert.isCloseTo(Double.valueOf(n), withPercentage(0.0)),
|
||||
doubleAssert.isEqualTo(Double.valueOf(n)));
|
||||
doubleAssert.isCloseTo(n, offset(0.0)), doubleAssert.isCloseTo(n, withPercentage(0.0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -54,10 +50,7 @@ final class AssertJDoubleTemplates {
|
||||
AbstractDoubleAssert<?> before(AbstractDoubleAssert<?> doubleAssert, double n) {
|
||||
return Refaster.anyOf(
|
||||
doubleAssert.isNotCloseTo(n, offset(0.0)),
|
||||
doubleAssert.isNotCloseTo(Double.valueOf(n), offset(0.0)),
|
||||
doubleAssert.isNotCloseTo(n, withPercentage(0.0)),
|
||||
doubleAssert.isNotCloseTo(Double.valueOf(n), withPercentage(0.0)),
|
||||
doubleAssert.isNotEqualTo(Double.valueOf(n)));
|
||||
doubleAssert.isNotCloseTo(n, withPercentage(0.0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -36,11 +36,7 @@ final class AssertJFloatTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractFloatAssert<?> before(AbstractFloatAssert<?> floatAssert, float n) {
|
||||
return Refaster.anyOf(
|
||||
floatAssert.isCloseTo(n, offset(0F)),
|
||||
floatAssert.isCloseTo(Float.valueOf(n), offset(0F)),
|
||||
floatAssert.isCloseTo(n, withPercentage(0)),
|
||||
floatAssert.isCloseTo(Float.valueOf(n), withPercentage(0)),
|
||||
floatAssert.isEqualTo(Float.valueOf(n)));
|
||||
floatAssert.isCloseTo(n, offset(0F)), floatAssert.isCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -53,11 +49,7 @@ final class AssertJFloatTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractFloatAssert<?> before(AbstractFloatAssert<?> floatAssert, float n) {
|
||||
return Refaster.anyOf(
|
||||
floatAssert.isNotCloseTo(n, offset(0F)),
|
||||
floatAssert.isNotCloseTo(Float.valueOf(n), offset(0F)),
|
||||
floatAssert.isNotCloseTo(n, withPercentage(0)),
|
||||
floatAssert.isNotCloseTo(Float.valueOf(n), withPercentage(0)),
|
||||
floatAssert.isNotEqualTo(Float.valueOf(n)));
|
||||
floatAssert.isNotCloseTo(n, offset(0F)), floatAssert.isNotCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -15,11 +15,7 @@ final class AssertJIntegerTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractIntegerAssert<?> before(AbstractIntegerAssert<?> intAssert, int n) {
|
||||
return Refaster.anyOf(
|
||||
intAssert.isCloseTo(n, offset(0)),
|
||||
intAssert.isCloseTo(Integer.valueOf(n), offset(0)),
|
||||
intAssert.isCloseTo(n, withPercentage(0)),
|
||||
intAssert.isCloseTo(Integer.valueOf(n), withPercentage(0)),
|
||||
intAssert.isEqualTo(Integer.valueOf(n)));
|
||||
intAssert.isCloseTo(n, offset(0)), intAssert.isCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -32,11 +28,7 @@ final class AssertJIntegerTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractIntegerAssert<?> before(AbstractIntegerAssert<?> intAssert, int n) {
|
||||
return Refaster.anyOf(
|
||||
intAssert.isNotCloseTo(n, offset(0)),
|
||||
intAssert.isNotCloseTo(Integer.valueOf(n), offset(0)),
|
||||
intAssert.isNotCloseTo(n, withPercentage(0)),
|
||||
intAssert.isNotCloseTo(Integer.valueOf(n), withPercentage(0)),
|
||||
intAssert.isNotEqualTo(Integer.valueOf(n)));
|
||||
intAssert.isNotCloseTo(n, offset(0)), intAssert.isNotCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -15,11 +15,7 @@ final class AssertJLongTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractLongAssert<?> before(AbstractLongAssert<?> longAssert, long n) {
|
||||
return Refaster.anyOf(
|
||||
longAssert.isCloseTo(n, offset(0L)),
|
||||
longAssert.isCloseTo(Long.valueOf(n), offset(0L)),
|
||||
longAssert.isCloseTo(n, withPercentage(0)),
|
||||
longAssert.isCloseTo(Long.valueOf(n), withPercentage(0)),
|
||||
longAssert.isEqualTo(Long.valueOf(n)));
|
||||
longAssert.isCloseTo(n, offset(0L)), longAssert.isCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -32,11 +28,7 @@ final class AssertJLongTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractLongAssert<?> before(AbstractLongAssert<?> longAssert, long n) {
|
||||
return Refaster.anyOf(
|
||||
longAssert.isNotCloseTo(n, offset(0L)),
|
||||
longAssert.isNotCloseTo(Long.valueOf(n), offset(0L)),
|
||||
longAssert.isNotCloseTo(n, withPercentage(0)),
|
||||
longAssert.isNotCloseTo(Long.valueOf(n), withPercentage(0)),
|
||||
longAssert.isNotEqualTo(Long.valueOf(n)));
|
||||
longAssert.isNotCloseTo(n, offset(0L)), longAssert.isNotCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import java.util.Map;
|
||||
import org.assertj.core.api.AbstractMapAssert;
|
||||
|
||||
final class AssertJMapTemplates {
|
||||
private AssertJMapTemplates() {}
|
||||
|
||||
static final class AbstractMapAssertContainsExactlyInAnyOrderEntriesOf<K, V> {
|
||||
@BeforeTemplate
|
||||
AbstractMapAssert<?, ?, K, V> before(AbstractMapAssert<?, ?, K, V> mapAssert, Map<K, V> map) {
|
||||
return mapAssert.isEqualTo(map);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractMapAssert<?, ?, K, V> after(AbstractMapAssert<?, ?, K, V> mapAssert, Map<K, V> map) {
|
||||
return mapAssert.containsExactlyInAnyOrderEntriesOf(map);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractMapAssertContainsExactlyEntriesOf<K, V> {
|
||||
@BeforeTemplate
|
||||
AbstractMapAssert<?, ?, K, V> before(AbstractMapAssert<?, ?, K, V> mapAssert, K key, V value) {
|
||||
return mapAssert.containsExactlyInAnyOrderEntriesOf(ImmutableMap.of(key, value));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractMapAssert<?, ?, K, V> after(AbstractMapAssert<?, ?, K, V> mapAssert, K key, V value) {
|
||||
return mapAssert.containsExactlyEntriesOf(ImmutableMap.of(key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import org.assertj.core.api.AbstractBigDecimalAssert;
|
||||
@@ -18,7 +22,7 @@ import org.assertj.core.api.NumberAssert;
|
||||
final class AssertJNumberTemplates {
|
||||
private AssertJNumberTemplates() {}
|
||||
|
||||
static final class NumberIsPositive {
|
||||
static final class NumberAssertIsPositive {
|
||||
@BeforeTemplate
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> numberAssert) {
|
||||
return Refaster.anyOf(
|
||||
@@ -69,7 +73,7 @@ final class AssertJNumberTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
static final class NumberIsNotPositive {
|
||||
static final class NumberAssertIsNotPositive {
|
||||
@BeforeTemplate
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> numberAssert) {
|
||||
return Refaster.anyOf(
|
||||
@@ -120,7 +124,7 @@ final class AssertJNumberTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
static final class NumberIsNegative {
|
||||
static final class NumberAssertIsNegative {
|
||||
@BeforeTemplate
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> numberAssert) {
|
||||
return Refaster.anyOf(
|
||||
@@ -171,7 +175,7 @@ final class AssertJNumberTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
static final class NumberIsNotNegative {
|
||||
static final class NumberAssertIsNotNegative {
|
||||
@BeforeTemplate
|
||||
AbstractByteAssert<?> before(AbstractByteAssert<?> numberAssert) {
|
||||
return Refaster.anyOf(
|
||||
@@ -221,4 +225,40 @@ final class AssertJNumberTemplates {
|
||||
return numberAssert.isNotNegative();
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatIsOdd {
|
||||
@BeforeTemplate
|
||||
AbstractIntegerAssert<?> before(int number) {
|
||||
return assertThat(number % 2).isEqualTo(1);
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
AbstractLongAssert<?> before(long number) {
|
||||
return assertThat(number % 2).isEqualTo(1);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
NumberAssert<?, ?> after(long number) {
|
||||
return assertThat(number).isOdd();
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatIsEven {
|
||||
@BeforeTemplate
|
||||
AbstractIntegerAssert<?> before(int number) {
|
||||
return assertThat(number % 2).isEqualTo(0);
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
AbstractLongAssert<?> before(long number) {
|
||||
return assertThat(number % 2).isEqualTo(0);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
NumberAssert<?, ?> after(long number) {
|
||||
return assertThat(number).isEven();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -21,7 +21,7 @@ final class AssertJObjectTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectAssert<S> after(S object) {
|
||||
return assertThat(object).isInstanceOf(Refaster.<T>clazz());
|
||||
}
|
||||
@@ -34,7 +34,7 @@ final class AssertJObjectTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectAssert<S> after(S object) {
|
||||
return assertThat(object).isNotInstanceOf(Refaster.<T>clazz());
|
||||
}
|
||||
@@ -47,7 +47,7 @@ final class AssertJObjectTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectAssert<S> after(S object1, T object2) {
|
||||
return assertThat(object1).isEqualTo(object2);
|
||||
}
|
||||
@@ -60,7 +60,7 @@ final class AssertJObjectTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectAssert<S> after(S object1, T object2) {
|
||||
return assertThat(object1).isNotEqualTo(object2);
|
||||
}
|
||||
@@ -73,7 +73,7 @@ final class AssertJObjectTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectAssert<T> after(T object, String str) {
|
||||
return assertThat(object).hasToString(str);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -26,7 +26,7 @@ final class AssertJOptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, T> after(Optional<T> optional) {
|
||||
return assertThat(optional).get();
|
||||
}
|
||||
@@ -53,7 +53,7 @@ final class AssertJOptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
OptionalAssert<T> after(Optional<T> optional) {
|
||||
return assertThat(optional).isPresent();
|
||||
}
|
||||
@@ -80,7 +80,7 @@ final class AssertJOptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
OptionalAssert<T> after(Optional<T> optional) {
|
||||
return assertThat(optional).isEmpty();
|
||||
}
|
||||
@@ -97,12 +97,24 @@ final class AssertJOptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
AbstractOptionalAssert<?, T> after(AbstractOptionalAssert<?, T> optionalAssert, T value) {
|
||||
return optionalAssert.hasValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AbstractOptionalAssertContainsSame<T> {
|
||||
@BeforeTemplate
|
||||
AbstractAssert<?, ?> before(AbstractOptionalAssert<?, T> optionalAssert, T value) {
|
||||
return Refaster.anyOf(
|
||||
optionalAssert.get().isSameAs(value), optionalAssert.isPresent().isSameAs(value));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractOptionalAssert<?, T> after(AbstractOptionalAssert<?, T> optionalAssert, T value) {
|
||||
return optionalAssert.containsSame(value);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatOptionalHasValueMatching<T> {
|
||||
@BeforeTemplate
|
||||
AbstractOptionalAssert<?, T> before(Optional<T> optional, Predicate<? super T> predicate) {
|
||||
@@ -110,7 +122,7 @@ final class AssertJOptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, T> after(Optional<T> optional, Predicate<? super T> predicate) {
|
||||
return assertThat(optional).get().matches(predicate);
|
||||
}
|
||||
|
||||
@@ -15,11 +15,7 @@ final class AssertJShortTemplates {
|
||||
@BeforeTemplate
|
||||
AbstractShortAssert<?> before(AbstractShortAssert<?> shortAssert, short n) {
|
||||
return Refaster.anyOf(
|
||||
shortAssert.isCloseTo(n, offset((short) 0)),
|
||||
shortAssert.isCloseTo(Short.valueOf(n), offset((short) 0)),
|
||||
shortAssert.isCloseTo(n, withPercentage(0)),
|
||||
shortAssert.isCloseTo(Short.valueOf(n), withPercentage(0)),
|
||||
shortAssert.isEqualTo(Short.valueOf(n)));
|
||||
shortAssert.isCloseTo(n, offset((short) 0)), shortAssert.isCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -33,10 +29,7 @@ final class AssertJShortTemplates {
|
||||
AbstractShortAssert<?> before(AbstractShortAssert<?> shortAssert, short n) {
|
||||
return Refaster.anyOf(
|
||||
shortAssert.isNotCloseTo(n, offset((short) 0)),
|
||||
shortAssert.isNotCloseTo(Short.valueOf(n), offset((short) 0)),
|
||||
shortAssert.isNotCloseTo(n, withPercentage(0)),
|
||||
shortAssert.isNotCloseTo(Short.valueOf(n), withPercentage(0)),
|
||||
shortAssert.isNotEqualTo(Short.valueOf(n)));
|
||||
shortAssert.isNotCloseTo(n, withPercentage(0)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
@@ -31,7 +31,7 @@ final class AssertJStringTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(String string) {
|
||||
assertThat(string).isEmpty();
|
||||
}
|
||||
@@ -56,9 +56,35 @@ final class AssertJStringTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractAssert<?, ?> after(String string) {
|
||||
return assertThat(string).isNotEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatMatches {
|
||||
@BeforeTemplate
|
||||
AbstractAssert<?, ?> before(String string, String regex) {
|
||||
return assertThat(string.matches(regex)).isTrue();
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractAssert<?, ?> after(String string, String regex) {
|
||||
return assertThat(string).matches(regex);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatDoesNotMatch {
|
||||
@BeforeTemplate
|
||||
AbstractAssert<?, ?> before(String string, String regex) {
|
||||
return assertThat(string.matches(regex)).isFalse();
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractAssert<?, ?> after(String string, String regex) {
|
||||
return assertThat(string).doesNotMatch(regex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.common.collect.ImmutableBiMap;
|
||||
@@ -12,10 +13,10 @@ import com.google.common.collect.ImmutableSortedMultiset;
|
||||
import com.google.common.collect.ImmutableSortedSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.NotMatches;
|
||||
import com.google.errorprone.refaster.annotation.Repeated;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.util.ArrayList;
|
||||
@@ -38,6 +39,7 @@ import java.util.stream.Collector;
|
||||
import java.util.stream.Stream;
|
||||
import org.assertj.core.api.AbstractAssert;
|
||||
import org.assertj.core.api.AbstractBooleanAssert;
|
||||
import org.assertj.core.api.AbstractCollectionAssert;
|
||||
import org.assertj.core.api.AbstractComparableAssert;
|
||||
import org.assertj.core.api.AbstractDoubleAssert;
|
||||
import org.assertj.core.api.AbstractIntegerAssert;
|
||||
@@ -51,6 +53,7 @@ import org.assertj.core.api.ObjectEnumerableAssert;
|
||||
import org.assertj.core.api.OptionalDoubleAssert;
|
||||
import org.assertj.core.api.OptionalIntAssert;
|
||||
import org.assertj.core.api.OptionalLongAssert;
|
||||
import tech.picnic.errorprone.refaster.util.IsArray;
|
||||
|
||||
/** Refaster templates related to AssertJ expressions and statements. */
|
||||
// XXX: Most `AbstractIntegerAssert` rules can also be applied for other primitive types. Generate
|
||||
@@ -94,7 +97,6 @@ import org.assertj.core.api.OptionalLongAssert;
|
||||
// XXX: Right now we use and import `Offset.offset` and `Percentage.withPercentage`. Use the AssertJ
|
||||
// methods instead. (Also in the TestNG migration.)
|
||||
// ^ Also for `Tuple`!
|
||||
// XXX: Use `assertThatIllegalArgumentException` and variants.
|
||||
// XXX: `assertThatCode(x).isInstanceOf(clazz)` -> `assertThatThrownBy(x).isInstanceOf(clazz)`
|
||||
// (etc.)
|
||||
// XXX: Look into using Assertions#contentOf(URL url, Charset charset) instead of our own test
|
||||
@@ -134,7 +136,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
OptionalDoubleAssert after(OptionalDouble optional, double expected) {
|
||||
return assertThat(optional).hasValue(expected);
|
||||
}
|
||||
@@ -153,7 +155,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
OptionalIntAssert after(OptionalInt optional, int expected) {
|
||||
return assertThat(optional).hasValue(expected);
|
||||
}
|
||||
@@ -172,7 +174,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
OptionalLongAssert after(OptionalLong optional, long expected) {
|
||||
return assertThat(optional).hasValue(expected);
|
||||
}
|
||||
@@ -338,8 +340,14 @@ final class AssertJTemplates {
|
||||
ImmutableList.of(element),
|
||||
Arrays.asList(element),
|
||||
ImmutableSet.of(element),
|
||||
ImmutableMultiset.of(element))),
|
||||
iterAssert.containsExactlyInAnyOrder(element));
|
||||
ImmutableMultiset.of(element))));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("unchecked")
|
||||
ObjectEnumerableAssert<?, S> before2(
|
||||
ObjectEnumerableAssert<?, S> iterAssert, @NotMatches(IsArray.class) T element) {
|
||||
return iterAssert.containsExactlyInAnyOrder(element);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -349,16 +357,28 @@ final class AssertJTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatSetContainsExactlyOneElement<S, T extends S> {
|
||||
@BeforeTemplate
|
||||
ObjectEnumerableAssert<?, S> before(Set<S> set, T element) {
|
||||
return assertThat(set).containsOnly(element);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ObjectEnumerableAssert<?, S> after(Set<S> set, T element) {
|
||||
return assertThat(set).containsExactly(element);
|
||||
}
|
||||
}
|
||||
|
||||
static final class ObjectEnumerableContainsOneDistinctElement<S, T extends S> {
|
||||
@BeforeTemplate
|
||||
ObjectEnumerableAssert<?, S> before(ObjectEnumerableAssert<?, S> iterAssert, T element) {
|
||||
return Refaster.anyOf(
|
||||
iterAssert.hasSameElementsAs(
|
||||
Refaster.anyOf(
|
||||
ImmutableList.of(element),
|
||||
Arrays.asList(element),
|
||||
ImmutableSet.of(element),
|
||||
ImmutableMultiset.of(element))));
|
||||
return iterAssert.hasSameElementsAs(
|
||||
Refaster.anyOf(
|
||||
ImmutableList.of(element),
|
||||
Arrays.asList(element),
|
||||
ImmutableSet.of(element),
|
||||
ImmutableMultiset.of(element)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -371,13 +391,12 @@ final class AssertJTemplates {
|
||||
static final class ObjectEnumerableIsSubsetOfOneElement<S, T extends S> {
|
||||
@BeforeTemplate
|
||||
ObjectEnumerableAssert<?, S> before(ObjectEnumerableAssert<?, S> iterAssert, T element) {
|
||||
return Refaster.anyOf(
|
||||
iterAssert.isSubsetOf(
|
||||
Refaster.anyOf(
|
||||
ImmutableList.of(element),
|
||||
Arrays.asList(element),
|
||||
ImmutableSet.of(element),
|
||||
ImmutableMultiset.of(element))));
|
||||
return iterAssert.isSubsetOf(
|
||||
Refaster.anyOf(
|
||||
ImmutableList.of(element),
|
||||
Arrays.asList(element),
|
||||
ImmutableSet.of(element),
|
||||
ImmutableMultiset.of(element)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -395,8 +414,8 @@ final class AssertJTemplates {
|
||||
@BeforeTemplate
|
||||
void before(Iterable<E> iterable) {
|
||||
Refaster.anyOf(
|
||||
assertThat(iterable).hasSize(0),
|
||||
assertThat(iterable.iterator().hasNext()).isFalse(),
|
||||
assertThat(Iterables.size(iterable)).isEqualTo(0),
|
||||
assertThat(Iterables.size(iterable)).isEqualTo(0L),
|
||||
assertThat(Iterables.size(iterable)).isNotPositive());
|
||||
}
|
||||
@@ -405,13 +424,12 @@ final class AssertJTemplates {
|
||||
void before(Collection<E> iterable) {
|
||||
Refaster.anyOf(
|
||||
assertThat(iterable.isEmpty()).isTrue(),
|
||||
assertThat(iterable.size()).isEqualTo(0),
|
||||
assertThat(iterable.size()).isEqualTo(0L),
|
||||
assertThat(iterable.size()).isNotPositive());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Collection<E> iterable) {
|
||||
assertThat(iterable).isEmpty();
|
||||
}
|
||||
@@ -435,7 +453,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<E> after(Iterable<E> iterable) {
|
||||
return assertThat(iterable).isNotEmpty();
|
||||
}
|
||||
@@ -453,7 +471,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<E> after(Iterable<E> iterable, int length) {
|
||||
return assertThat(iterable).hasSize(length);
|
||||
}
|
||||
@@ -466,7 +484,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<S> after(Iterable<S> iterable, T element) {
|
||||
return assertThat(iterable).containsExactly(element);
|
||||
}
|
||||
@@ -483,7 +501,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<S> after(Iterable<S> iterable, T element) {
|
||||
return assertThat(iterable).containsExactly(element);
|
||||
}
|
||||
@@ -500,7 +518,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(List<S> list1, List<T> list2) {
|
||||
return assertThat(list1).containsExactlyElementsOf(list2);
|
||||
}
|
||||
@@ -512,15 +530,15 @@ final class AssertJTemplates {
|
||||
|
||||
static final class AssertThatSetsAreEqual<S, T extends S> {
|
||||
@BeforeTemplate
|
||||
IterableAssert<S> before(Set<S> set1, Set<T> set2) {
|
||||
AbstractCollectionAssert<?, ?, S, ?> before(Set<S> set1, Set<T> set2) {
|
||||
return Refaster.anyOf(
|
||||
assertThat(set1).isEqualTo(set2),
|
||||
assertThat(set1).containsExactlyInAnyOrderElementsOf(set2));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<S> after(Set<S> set1, Set<T> set2) {
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractCollectionAssert<?, ?, S, ?> after(Set<S> set1, Set<T> set2) {
|
||||
return assertThat(set1).hasSameElementsAs(set2);
|
||||
}
|
||||
}
|
||||
@@ -531,13 +549,13 @@ final class AssertJTemplates {
|
||||
|
||||
static final class AssertThatMultisetsAreEqual<S, T extends S> {
|
||||
@BeforeTemplate
|
||||
IterableAssert<S> before(Multiset<S> multiset1, Multiset<T> multiset2) {
|
||||
AbstractCollectionAssert<?, ?, S, ?> before(Multiset<S> multiset1, Multiset<T> multiset2) {
|
||||
return assertThat(multiset1).isEqualTo(multiset2);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
IterableAssert<S> after(Multiset<S> multiset1, Multiset<T> multiset2) {
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractCollectionAssert<?, ?, S, ?> after(Multiset<S> multiset1, Multiset<T> multiset2) {
|
||||
return assertThat(multiset1).containsExactlyInAnyOrderElementsOf(multiset2);
|
||||
}
|
||||
}
|
||||
@@ -602,8 +620,8 @@ final class AssertJTemplates {
|
||||
@BeforeTemplate
|
||||
void before(Map<K, V> map) {
|
||||
Refaster.anyOf(
|
||||
assertThat(map).hasSize(0),
|
||||
assertThat(map.isEmpty()).isTrue(),
|
||||
assertThat(map.size()).isEqualTo(0),
|
||||
assertThat(map.size()).isEqualTo(0L),
|
||||
assertThat(map.size()).isNotPositive());
|
||||
}
|
||||
@@ -614,7 +632,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Map<K, V> map) {
|
||||
assertThat(map).isEmpty();
|
||||
}
|
||||
@@ -651,7 +669,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map) {
|
||||
return assertThat(map).isNotEmpty();
|
||||
}
|
||||
@@ -666,7 +684,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map, int length) {
|
||||
return assertThat(map).hasSize(length);
|
||||
}
|
||||
@@ -680,7 +698,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map1, Map<K, V> map2) {
|
||||
return assertThat(map1).hasSameSizeAs(map2);
|
||||
}
|
||||
@@ -694,7 +712,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map, K key) {
|
||||
return assertThat(map).containsKey(key);
|
||||
}
|
||||
@@ -707,7 +725,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map, K key) {
|
||||
return assertThat(map).doesNotContainKey(key);
|
||||
}
|
||||
@@ -720,7 +738,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
MapAssert<K, V> after(Map<K, V> map, K key, V value) {
|
||||
return assertThat(map).containsEntry(key, value);
|
||||
}
|
||||
@@ -745,7 +763,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsAnyElementsOf(iterable);
|
||||
}
|
||||
@@ -766,7 +784,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).containsAnyOf(array);
|
||||
}
|
||||
@@ -775,19 +793,22 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsAnyOfVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsAnyOf" /* Varargs converted to array. */)
|
||||
IterableAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Iterable<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsAnyOf(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsAnyOf" /* Varargs converted to array. */)
|
||||
ListAssert<T> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsAnyOf(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@SuppressWarnings("ObjectEnumerableContainsOneElement" /* Not a true singleton. */)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsAnyOf(elements);
|
||||
}
|
||||
@@ -808,7 +829,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsAll(iterable);
|
||||
}
|
||||
@@ -829,7 +850,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).contains(array);
|
||||
}
|
||||
@@ -838,19 +859,21 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContains" /* Varargs converted to array. */)
|
||||
IterableAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Iterable<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).contains(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContains" /* Varargs converted to array. */)
|
||||
ListAssert<T> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).contains(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).contains(elements);
|
||||
}
|
||||
@@ -865,7 +888,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsExactlyElementsOf(iterable);
|
||||
}
|
||||
@@ -880,7 +903,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).containsExactly(array);
|
||||
}
|
||||
@@ -889,13 +912,14 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsExactlyVarargs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsExactly" /* Varargs converted to array. */)
|
||||
ListAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsExactly(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsExactly(elements);
|
||||
}
|
||||
@@ -911,13 +935,13 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
IterableAssert<T> before2(
|
||||
AbstractCollectionAssert<?, ?, T, ?> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Multiset<T>> collector, Iterable<U> iterable) {
|
||||
return assertThat(stream.collect(collector)).containsExactlyInAnyOrderElementsOf(iterable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsExactlyInAnyOrderElementsOf(iterable);
|
||||
}
|
||||
@@ -932,13 +956,13 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
IterableAssert<T> before2(
|
||||
AbstractCollectionAssert<?, ?, T, ?> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Multiset<T>> collector, U[] array) {
|
||||
return assertThat(stream.collect(collector)).containsExactlyInAnyOrder(array);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).containsExactlyInAnyOrder(array);
|
||||
}
|
||||
@@ -947,6 +971,7 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsExactlyInAnyOrderVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsExactlyInAnyOrder" /* Varargs converted to array. */)
|
||||
ListAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector))
|
||||
@@ -954,14 +979,16 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
IterableAssert<T> before2(
|
||||
@SuppressWarnings("AssertThatStreamContainsExactlyInAnyOrder" /* Varargs converted to array. */)
|
||||
AbstractCollectionAssert<?, ?, T, ?> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Multiset<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector))
|
||||
.containsExactlyInAnyOrder(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@SuppressWarnings("ObjectEnumerableContainsExactlyOneElement" /* Not a true singleton. */)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsExactlyInAnyOrder(elements);
|
||||
}
|
||||
@@ -982,7 +1009,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsSequence(iterable);
|
||||
}
|
||||
@@ -991,13 +1018,15 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsSequenceVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsSequence" /* Varargs converted to array. */)
|
||||
ListAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsSequence(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@SuppressWarnings("ObjectEnumerableContainsOneElement" /* Not a true singleton. */)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsSequence(elements);
|
||||
}
|
||||
@@ -1018,7 +1047,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).containsSubsequence(iterable);
|
||||
}
|
||||
@@ -1027,6 +1056,7 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsSubsequenceVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsSubsequence" /* Varargs converted to array. */)
|
||||
ListAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector))
|
||||
@@ -1034,7 +1064,8 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@SuppressWarnings("ObjectEnumerableContainsOneElement" /* Not a true singleton. */)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsSubsequence(elements);
|
||||
}
|
||||
@@ -1055,7 +1086,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).doesNotContainAnyElementsOf(iterable);
|
||||
}
|
||||
@@ -1076,7 +1107,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).doesNotContain(array);
|
||||
}
|
||||
@@ -1085,19 +1116,21 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamDoesNotContainVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamDoesNotContain" /* Varargs converted to array. */)
|
||||
IterableAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Iterable<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).doesNotContain(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamDoesNotContain" /* Varargs converted to array. */)
|
||||
ListAssert<T> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).doesNotContain(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).doesNotContain(elements);
|
||||
}
|
||||
@@ -1118,7 +1151,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).doesNotContainSequence(iterable);
|
||||
}
|
||||
@@ -1127,6 +1160,7 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamDoesNotContainSequenceVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamDoesNotContainSequence" /* Varargs converted to array. */)
|
||||
ListAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector))
|
||||
@@ -1134,7 +1168,8 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@SuppressWarnings("ObjectEnumerableDoesNotContainOneElement" /* Not a true singleton. */)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).doesNotContainSequence(elements);
|
||||
}
|
||||
@@ -1155,7 +1190,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, Iterable<U> iterable) {
|
||||
return assertThat(stream).hasSameElementsAs(iterable);
|
||||
}
|
||||
@@ -1176,7 +1211,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] array) {
|
||||
return assertThat(stream).containsOnly(array);
|
||||
}
|
||||
@@ -1185,19 +1220,21 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamContainsOnlyVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsOnly" /* Varargs converted to array. */)
|
||||
IterableAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Iterable<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsOnly(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamContainsOnly" /* Varargs converted to array. */)
|
||||
ListAssert<T> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).containsOnly(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).containsOnly(elements);
|
||||
}
|
||||
@@ -1230,7 +1267,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, U[] iterable) {
|
||||
return assertThat(stream).isSubsetOf(iterable);
|
||||
}
|
||||
@@ -1239,19 +1276,21 @@ final class AssertJTemplates {
|
||||
// XXX: This rule assumes the `collector` doesn't completely discard certain values.
|
||||
static final class AssertThatStreamIsSubsetOfVarArgs<S, T extends S, U extends T> {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamIsSubsetOf" /* Varargs converted to array. */)
|
||||
IterableAssert<T> before(
|
||||
Stream<S> stream, Collector<S, ?, ? extends Iterable<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).isSubsetOf(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatStreamIsSubsetOf" /* Varargs converted to array. */)
|
||||
ListAssert<T> before2(
|
||||
Stream<S> stream, Collector<S, ?, ? extends List<T>> collector, @Repeated U elements) {
|
||||
return assertThat(stream.collect(collector)).isSubsetOf(Refaster.asVarargs(elements));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ListAssert<S> after(Stream<S> stream, @Repeated U elements) {
|
||||
return assertThat(stream).isSubsetOf(elements);
|
||||
}
|
||||
@@ -1270,7 +1309,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Stream<S> stream) {
|
||||
assertThat(stream).isEmpty();
|
||||
}
|
||||
@@ -1289,7 +1328,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Stream<S> stream) {
|
||||
assertThat(stream).isNotEmpty();
|
||||
}
|
||||
@@ -1302,7 +1341,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Stream<T> stream, int size) {
|
||||
assertThat(stream).hasSize(size);
|
||||
}
|
||||
@@ -1319,7 +1358,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Predicate<T> predicate, T object) {
|
||||
assertThat(predicate).accepts(object);
|
||||
}
|
||||
@@ -1332,7 +1371,7 @@ final class AssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Predicate<T> predicate, T object) {
|
||||
assertThat(predicate).rejects(object);
|
||||
}
|
||||
@@ -2173,7 +2212,7 @@ final class AssertJTemplates {
|
||||
// }
|
||||
//
|
||||
// @AfterTemplate
|
||||
// @UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
// @UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
// IterableAssert<E> after(Iterable<E> iterable, E expected) {
|
||||
// return assertThat(iterable).containsExactly(expected);
|
||||
// }
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.assertj.core.api.Assertions.assertThatIOException;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
|
||||
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
|
||||
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.Repeated;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.io.IOException;
|
||||
import org.assertj.core.api.AbstractObjectAssert;
|
||||
import org.assertj.core.api.AbstractThrowableAssert;
|
||||
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
|
||||
|
||||
/**
|
||||
* Refaster templates related to AssertJ assertions over expressions that may throw a {@link
|
||||
* Throwable} subtype.
|
||||
*
|
||||
* <p>For reasons of consistency we prefer {@link
|
||||
* org.assertj.core.api.Assertions#assertThatThrownBy} over static methods for specific exception
|
||||
* types. Note that only the most common assertion expressions are rewritten here; covering all
|
||||
* cases would require the implementation of an Error Prone check instead.
|
||||
*/
|
||||
final class AssertJThrowingCallableTemplates {
|
||||
private AssertJThrowingCallableTemplates() {}
|
||||
|
||||
static final class AssertThatThrownByIllegalArgumentException {
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable) {
|
||||
return assertThatIllegalArgumentException().isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalArgumentExceptionHasMessage {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalArgumentException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalArgumentException().isThrownBy(throwingCallable).withMessage(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalArgumentExceptionHasMessageStartingWith {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalArgumentException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalArgumentException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageStartingWith(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageStartingWith(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalArgumentExceptionHasMessageContaining {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalArgumentException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalArgumentException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageContaining(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalArgumentExceptionHasMessageNotContainingAny {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalArgumentException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(
|
||||
ThrowingCallable throwingCallable, @Repeated CharSequence values) {
|
||||
return assertThatIllegalArgumentException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageNotContainingAny(values);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(
|
||||
ThrowingCallable throwingCallable, @Repeated CharSequence values) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageNotContainingAny(values);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalStateException {
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable) {
|
||||
return assertThatIllegalStateException().isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalStateExceptionHasMessage {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalStateException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalStateException().isThrownBy(throwingCallable).withMessage(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalStateExceptionHasMessageStartingWith {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalStateException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalStateException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageStartingWith(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageStartingWith(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalStateExceptionHasMessageContaining {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalStateException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalStateException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageContaining(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIllegalStateExceptionHasMessageNotContaining {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIllegalStateException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIllegalStateException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageNotContaining(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageNotContaining(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByNullPointerException {
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable) {
|
||||
return assertThatNullPointerException().isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(NullPointerException.class);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByNullPointerExceptionHasMessage {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByNullPointerException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatNullPointerException().isThrownBy(throwingCallable).withMessage(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByNullPointerExceptionHasMessageStartingWith {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByNullPointerException" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatNullPointerException()
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessageStartingWith(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(NullPointerException.class)
|
||||
.hasMessageStartingWith(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIOException {
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable) {
|
||||
return assertThatIOException().isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(IOException.class);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByIOExceptionHasMessage {
|
||||
@SuppressWarnings(
|
||||
"AssertThatThrownByIOException" /* Matches strictly more specific expressions. */)
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatIOException().isThrownBy(throwingCallable).withMessage(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(ThrowingCallable throwingCallable, String message) {
|
||||
return assertThatThrownBy(throwingCallable)
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownBy {
|
||||
@BeforeTemplate
|
||||
AbstractObjectAssert<?, ?> before(
|
||||
Class<? extends Throwable> exceptionType, ThrowingCallable throwingCallable) {
|
||||
return assertThatExceptionOfType(exceptionType).isThrownBy(throwingCallable);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(
|
||||
Class<? extends Throwable> exceptionType, ThrowingCallable throwingCallable) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(exceptionType);
|
||||
}
|
||||
}
|
||||
|
||||
static final class AssertThatThrownByHasMessage {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("AssertThatThrownBy" /* Matches strictly more specific expressions. */)
|
||||
AbstractObjectAssert<?, ?> before(
|
||||
Class<? extends Throwable> exceptionType,
|
||||
ThrowingCallable throwingCallable,
|
||||
String message) {
|
||||
return assertThatExceptionOfType(exceptionType)
|
||||
.isThrownBy(throwingCallable)
|
||||
.withMessage(message);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
AbstractObjectAssert<?, ?> after(
|
||||
Class<? extends Throwable> exceptionType,
|
||||
ThrowingCallable throwingCallable,
|
||||
String message) {
|
||||
return assertThatThrownBy(throwingCallable).isInstanceOf(exceptionType).hasMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
// XXX: Drop this template in favour of a generic Error Prone check which flags
|
||||
// `String.format(...)` arguments to a wide range of format methods.
|
||||
static final class AbstractThrowableAssertHasMessage {
|
||||
@BeforeTemplate
|
||||
AbstractThrowableAssert<?, ? extends Throwable> before(
|
||||
AbstractThrowableAssert<?, ? extends Throwable> abstractThrowableAssert,
|
||||
String message,
|
||||
@Repeated Object parameters) {
|
||||
return abstractThrowableAssert.hasMessage(String.format(message, parameters));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractThrowableAssert<?, ? extends Throwable> after(
|
||||
AbstractThrowableAssert<?, ? extends Throwable> abstractThrowableAssert,
|
||||
String message,
|
||||
@Repeated Object parameters) {
|
||||
return abstractThrowableAssert.hasMessage(message, parameters);
|
||||
}
|
||||
}
|
||||
|
||||
// XXX: Drop this template in favour of a generic Error Prone check which flags
|
||||
// `String.format(...)` arguments to a wide range of format methods.
|
||||
static final class AbstractThrowableAssertWithFailMessage {
|
||||
@BeforeTemplate
|
||||
AbstractThrowableAssert<?, ? extends Throwable> before(
|
||||
AbstractThrowableAssert<?, ? extends Throwable> abstractThrowableAssert,
|
||||
String message,
|
||||
@Repeated Object args) {
|
||||
return abstractThrowableAssert.withFailMessage(String.format(message, args));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
AbstractThrowableAssert<?, ? extends Throwable> after(
|
||||
AbstractThrowableAssert<?, ? extends Throwable> abstractThrowableAssert,
|
||||
String message,
|
||||
@Repeated Object args) {
|
||||
return abstractThrowableAssert.withFailMessage(message, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.base.Preconditions.checkElementIndex;
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static com.google.common.collect.Sets.toImmutableEnumSet;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Collections.disjoint;
|
||||
import static java.util.Objects.checkIndex;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.common.base.Splitter;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Iterators;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -38,12 +40,12 @@ final class AssortedTemplates {
|
||||
static final class CheckIndex {
|
||||
@BeforeTemplate
|
||||
int before(int index, int size) {
|
||||
return Preconditions.checkElementIndex(index, size);
|
||||
return checkElementIndex(index, size);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
int after(int index, int size) {
|
||||
return Objects.checkIndex(index, size);
|
||||
return checkIndex(index, size);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,14 +64,14 @@ final class AssortedTemplates {
|
||||
}
|
||||
|
||||
static final class MapGetOrNull<K, V, L> {
|
||||
@Nullable
|
||||
@BeforeTemplate
|
||||
@Nullable
|
||||
V before(Map<K, V> map, L key) {
|
||||
return map.getOrDefault(key, null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@AfterTemplate
|
||||
@Nullable
|
||||
V after(Map<K, V> map, L key) {
|
||||
return map.get(key);
|
||||
}
|
||||
@@ -91,7 +93,7 @@ final class AssortedTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableSet<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableEnumSet());
|
||||
}
|
||||
@@ -107,8 +109,8 @@ final class AssortedTemplates {
|
||||
Streams.stream(iterator).findAny().orElse(defaultValue));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@AfterTemplate
|
||||
@Nullable
|
||||
T after(Iterator<T> iterator, T defaultValue) {
|
||||
return Iterators.getNext(iterator, defaultValue);
|
||||
}
|
||||
@@ -161,7 +163,7 @@ final class AssortedTemplates {
|
||||
|
||||
@AfterTemplate
|
||||
boolean after(Set<T> set1, Set<T> set2) {
|
||||
return Collections.disjoint(set1, set2);
|
||||
return disjoint(set1, set2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,15 +178,15 @@ final class AssortedTemplates {
|
||||
@BeforeTemplate
|
||||
boolean before(Collection<T> collection1, Collection<T> collection2) {
|
||||
return Refaster.anyOf(
|
||||
Collections.disjoint(ImmutableSet.copyOf(collection1), collection2),
|
||||
Collections.disjoint(new HashSet<>(collection1), collection2),
|
||||
Collections.disjoint(collection1, ImmutableSet.copyOf(collection2)),
|
||||
Collections.disjoint(collection1, new HashSet<>(collection2)));
|
||||
disjoint(ImmutableSet.copyOf(collection1), collection2),
|
||||
disjoint(new HashSet<>(collection1), collection2),
|
||||
disjoint(collection1, ImmutableSet.copyOf(collection2)),
|
||||
disjoint(collection1, new HashSet<>(collection2)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
boolean after(Collection<T> collection1, Collection<T> collection2) {
|
||||
return Collections.disjoint(collection1, collection2);
|
||||
return disjoint(collection1, collection2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,11 +258,6 @@ final class AssortedTemplates {
|
||||
//
|
||||
// @BeforeTemplate
|
||||
// void before(Supplier<T> supplier) {
|
||||
// anyStatement(supplier::get);
|
||||
// }
|
||||
//
|
||||
// @BeforeTemplate
|
||||
// void before2(Supplier<T> supplier) {
|
||||
// anyStatement(() -> supplier.get());
|
||||
// }
|
||||
//
|
||||
|
||||
@@ -187,7 +187,7 @@ final class CollectionTemplates {
|
||||
* Don't call {@link ImmutableCollection#asList()} if the result is going to be streamed; stream
|
||||
* directly.
|
||||
*/
|
||||
static final class ImmutableCollectionAsListToStream<T> {
|
||||
static final class ImmutableCollectionStream<T> {
|
||||
@BeforeTemplate
|
||||
Stream<T> before(ImmutableCollection<T> collection) {
|
||||
return collection.asList().stream();
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Comparator.comparing;
|
||||
import static java.util.Comparator.comparingDouble;
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.Comparator.comparingLong;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
import static java.util.function.Function.identity;
|
||||
|
||||
import com.google.common.collect.Comparators;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -29,14 +34,13 @@ final class ComparatorTemplates {
|
||||
@BeforeTemplate
|
||||
Comparator<T> before() {
|
||||
return Refaster.anyOf(
|
||||
Comparator.comparing(Refaster.anyOf(identity(), v -> v)),
|
||||
Comparator.<T>reverseOrder().reversed());
|
||||
comparing(Refaster.anyOf(identity(), v -> v)), Comparator.<T>reverseOrder().reversed());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<T> after() {
|
||||
return Comparator.naturalOrder();
|
||||
return naturalOrder();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +52,7 @@ final class ComparatorTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<T> after() {
|
||||
return reverseOrder();
|
||||
}
|
||||
@@ -58,11 +62,11 @@ final class ComparatorTemplates {
|
||||
// XXX: Drop the `Refaster.anyOf` if/when we decide to rewrite one to the other.
|
||||
@BeforeTemplate
|
||||
Comparator<T> before(Comparator<T> cmp) {
|
||||
return Comparator.comparing(Refaster.anyOf(identity(), v -> v), cmp);
|
||||
return comparing(Refaster.anyOf(identity(), v -> v), cmp);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<T> after(Comparator<T> cmp) {
|
||||
return cmp;
|
||||
}
|
||||
@@ -72,7 +76,7 @@ final class ComparatorTemplates {
|
||||
static final class ThenComparing<S, T extends Comparable<? super T>> {
|
||||
@BeforeTemplate
|
||||
Comparator<S> before(Comparator<S> cmp, Function<? super S, ? extends T> function) {
|
||||
return cmp.thenComparing(Comparator.comparing(function));
|
||||
return cmp.thenComparing(comparing(function));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -85,11 +89,11 @@ final class ComparatorTemplates {
|
||||
static final class ThenComparingReversed<S, T extends Comparable<? super T>> {
|
||||
@BeforeTemplate
|
||||
Comparator<S> before(Comparator<S> cmp, Function<? super S, ? extends T> function) {
|
||||
return cmp.thenComparing(Comparator.comparing(function).reversed());
|
||||
return cmp.thenComparing(comparing(function).reversed());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<S> after(Comparator<S> cmp, Function<? super S, ? extends T> function) {
|
||||
return cmp.thenComparing(function, reverseOrder());
|
||||
}
|
||||
@@ -100,7 +104,7 @@ final class ComparatorTemplates {
|
||||
@BeforeTemplate
|
||||
Comparator<S> before(
|
||||
Comparator<S> cmp, Function<? super S, ? extends T> function, Comparator<? super T> cmp2) {
|
||||
return cmp.thenComparing(Comparator.comparing(function, cmp2));
|
||||
return cmp.thenComparing(comparing(function, cmp2));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -115,7 +119,7 @@ final class ComparatorTemplates {
|
||||
@BeforeTemplate
|
||||
Comparator<S> before(
|
||||
Comparator<S> cmp, Function<? super S, ? extends T> function, Comparator<? super T> cmp2) {
|
||||
return cmp.thenComparing(Comparator.comparing(function, cmp2).reversed());
|
||||
return cmp.thenComparing(comparing(function, cmp2).reversed());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -129,7 +133,7 @@ final class ComparatorTemplates {
|
||||
static final class ThenComparingDouble<T> {
|
||||
@BeforeTemplate
|
||||
Comparator<T> before(Comparator<T> cmp, ToDoubleFunction<? super T> function) {
|
||||
return cmp.thenComparing(Comparator.comparingDouble(function));
|
||||
return cmp.thenComparing(comparingDouble(function));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -142,7 +146,7 @@ final class ComparatorTemplates {
|
||||
static final class ThenComparingInt<T> {
|
||||
@BeforeTemplate
|
||||
Comparator<T> before(Comparator<T> cmp, ToIntFunction<? super T> function) {
|
||||
return cmp.thenComparing(Comparator.comparingInt(function));
|
||||
return cmp.thenComparing(comparingInt(function));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -155,7 +159,7 @@ final class ComparatorTemplates {
|
||||
static final class ThenComparingLong<T> {
|
||||
@BeforeTemplate
|
||||
Comparator<T> before(Comparator<T> cmp, ToLongFunction<? super T> function) {
|
||||
return cmp.thenComparing(Comparator.comparingLong(function));
|
||||
return cmp.thenComparing(comparingLong(function));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -176,9 +180,9 @@ final class ComparatorTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<T> after(Comparator<T> cmp) {
|
||||
return cmp.thenComparing(Comparator.naturalOrder());
|
||||
return cmp.thenComparing(naturalOrder());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -233,10 +233,7 @@ final class DoubleStreamTemplates {
|
||||
static final class DoubleStreamAllMatch {
|
||||
@BeforeTemplate
|
||||
boolean before(DoubleStream stream, DoublePredicate predicate) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(predicate.negate()),
|
||||
!stream.anyMatch(predicate.negate()),
|
||||
stream.filter(predicate.negate()).findAny().isEmpty());
|
||||
return stream.noneMatch(predicate.negate());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -251,10 +248,7 @@ final class DoubleStreamTemplates {
|
||||
|
||||
@BeforeTemplate
|
||||
boolean before(DoubleStream stream) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(e -> !test(e)),
|
||||
!stream.anyMatch(e -> !test(e)),
|
||||
stream.filter(e -> !test(e)).findAny().isEmpty());
|
||||
return stream.noneMatch(e -> !test(e));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.AlsoNegation;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.NoAutoboxing;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@@ -12,26 +11,9 @@ import java.util.function.Predicate;
|
||||
final class EqualityTemplates {
|
||||
private EqualityTemplates() {}
|
||||
|
||||
/** Prefer primitive/reference-based quality for primitives and enums. */
|
||||
static final class PrimitiveOrReferenceEquality {
|
||||
@NoAutoboxing
|
||||
@BeforeTemplate
|
||||
boolean before(boolean a, boolean b) {
|
||||
return Objects.equals(a, b);
|
||||
}
|
||||
|
||||
@NoAutoboxing
|
||||
@BeforeTemplate
|
||||
boolean before(long a, long b) {
|
||||
return Objects.equals(a, b);
|
||||
}
|
||||
|
||||
@NoAutoboxing
|
||||
@BeforeTemplate
|
||||
boolean before(double a, double b) {
|
||||
return Objects.equals(a, b);
|
||||
}
|
||||
|
||||
/** Prefer reference-based quality for enums. */
|
||||
// Primitive value comparisons are not listed, because Error Prone flags those out of the box.
|
||||
static final class PrimitiveOrReferenceEquality<T extends Enum<T>> {
|
||||
/**
|
||||
* Enums can be compared by reference. It is safe to do so even in the face of refactorings,
|
||||
* because if the type is ever converted to a non-enum, then Error-Prone will complain about any
|
||||
@@ -40,13 +22,13 @@ final class EqualityTemplates {
|
||||
// XXX: This Refaster rule is the topic of https://github.com/google/error-prone/issues/559. We
|
||||
// work around the issue by selecting the "largest replacements". See RefasterCheck.
|
||||
@BeforeTemplate
|
||||
<T extends Enum<T>> boolean before(T a, T b) {
|
||||
boolean before(T a, T b) {
|
||||
return Refaster.anyOf(a.equals(b), Objects.equals(a, b));
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
boolean after(boolean a, boolean b) {
|
||||
@AlsoNegation
|
||||
boolean after(T a, T b) {
|
||||
return a == b;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableListMultimap.flatteningToImmutableListMultimap;
|
||||
import static com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.function.Function.identity;
|
||||
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
@@ -12,7 +13,6 @@ import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.SetMultimap;
|
||||
import com.google.common.collect.SortedSetMultimap;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -56,10 +56,7 @@ final class ImmutableListMultimapTemplates {
|
||||
static final class EmptyImmutableListMultimap<K, V> {
|
||||
@BeforeTemplate
|
||||
ImmutableMultimap<K, V> before() {
|
||||
return Refaster.anyOf(
|
||||
ImmutableListMultimap.<K, V>builder().build(),
|
||||
ImmutableMultimap.<K, V>builder().build(),
|
||||
ImmutableMultimap.of());
|
||||
return Refaster.anyOf(ImmutableListMultimap.<K, V>builder().build(), ImmutableMultimap.of());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -80,7 +77,6 @@ final class ImmutableListMultimapTemplates {
|
||||
ImmutableMultimap<K, V> before(K key, V value) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableListMultimap.<K, V>builder().put(key, value).build(),
|
||||
ImmutableMultimap.<K, V>builder().put(key, value).build(),
|
||||
ImmutableMultimap.of(key, value));
|
||||
}
|
||||
|
||||
@@ -99,9 +95,8 @@ final class ImmutableListMultimapTemplates {
|
||||
ImmutableMultimap<K, V> before(Map.Entry<? extends K, ? extends V> entry) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableListMultimap.<K, V>builder().put(entry).build(),
|
||||
Stream.of(entry).collect(toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue)),
|
||||
ImmutableMultimap.<K, V>builder().put(entry).build(),
|
||||
ImmutableMultimap.of(entry.getKey(), entry.getValue()));
|
||||
Stream.of(entry)
|
||||
.collect(toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -118,8 +113,7 @@ final class ImmutableListMultimapTemplates {
|
||||
ImmutableListMultimap.copyOf(iterable.entries()),
|
||||
ImmutableListMultimap.<K, V>builder().putAll(iterable).build(),
|
||||
ImmutableMultimap.copyOf(iterable),
|
||||
ImmutableMultimap.copyOf(iterable.entries()),
|
||||
ImmutableMultimap.<K, V>builder().putAll(iterable).build());
|
||||
ImmutableMultimap.copyOf(iterable.entries()));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
@@ -129,7 +123,6 @@ final class ImmutableListMultimapTemplates {
|
||||
ImmutableListMultimap.<K, V>builder().putAll(iterable).build(),
|
||||
Streams.stream(iterable)
|
||||
.collect(toImmutableListMultimap(Map.Entry::getKey, Map.Entry::getValue)),
|
||||
ImmutableMultimap.<K, V>builder().putAll(iterable).build(),
|
||||
ImmutableMultimap.copyOf(iterable));
|
||||
}
|
||||
|
||||
@@ -168,7 +161,7 @@ final class ImmutableListMultimapTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableListMultimap<K, V> after(Stream<E> stream) {
|
||||
return stream.collect(toImmutableListMultimap(e -> keyFunction(e), e -> valueFunction(e)));
|
||||
}
|
||||
@@ -279,17 +272,4 @@ final class ImmutableListMultimapTemplates {
|
||||
return ImmutableListMultimap.copyOf(Multimaps.transformValues(multimap, transformation));
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily copy an {@link ImmutableListMultimap}. */
|
||||
static final class ImmutableListMultimapCopyOfImmutableListMultimap<K, V> {
|
||||
@BeforeTemplate
|
||||
ImmutableListMultimap<K, V> before(ImmutableListMultimap<K, V> multimap) {
|
||||
return ImmutableListMultimap.copyOf(multimap);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableListMultimap<K, V> after(ImmutableListMultimap<K, V> multimap) {
|
||||
return multimap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableList.toImmutableList;
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
@@ -9,14 +12,12 @@ import static java.util.stream.Collectors.toList;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
@@ -41,37 +42,6 @@ final class ImmutableListTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableList#of()} over more contrived alternatives. */
|
||||
static final class EmptyImmutableList<T> {
|
||||
@BeforeTemplate
|
||||
ImmutableList<T> before() {
|
||||
return Refaster.anyOf(
|
||||
ImmutableList.<T>builder().build(), Stream.<T>empty().collect(toImmutableList()));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after() {
|
||||
return ImmutableList.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object)} over alternatives that don't communicate the
|
||||
* immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Note that this rewrite rule is incorrect for nullable elements.
|
||||
static final class SingletonImmutableList<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T element) {
|
||||
return Collections.singletonList(element);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T secondName) {
|
||||
return ImmutableList.of(secondName);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#copyOf(Iterable)} and variants over more contrived alternatives.
|
||||
*/
|
||||
@@ -118,30 +88,16 @@ final class ImmutableListTemplates {
|
||||
ImmutableList<T> before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableList.copyOf(stream.iterator()),
|
||||
ImmutableList.copyOf(stream::iterator),
|
||||
stream.collect(collectingAndThen(toList(), ImmutableList::copyOf)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableList<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableList());
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't call {@link ImmutableList#asList()}; it is a no-op. */
|
||||
static final class ImmutableListAsList<T> {
|
||||
@BeforeTemplate
|
||||
ImmutableList<T> before(ImmutableList<T> list) {
|
||||
return list.asList();
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(ImmutableList<T> list) {
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableList#sortedCopyOf(Iterable)} over more contrived alternatives. */
|
||||
static final class ImmutableListSortedCopyOf<T extends Comparable<? super T>> {
|
||||
@BeforeTemplate
|
||||
@@ -195,9 +151,122 @@ final class ImmutableListTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableList<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableSet()).asList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of()} over more contrived alternatives or alternatives that don't
|
||||
* communicate the immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: The `Stream` variant may be too contrived to warrant inclusion. Review its usage if/when
|
||||
// this and similar Refaster templates are replaced with an Error Prone check.
|
||||
static final class ImmutableListOf<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before() {
|
||||
return Refaster.anyOf(
|
||||
ImmutableList.<T>builder().build(),
|
||||
Stream.<T>empty().collect(toImmutableList()),
|
||||
emptyList(),
|
||||
List.of());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after() {
|
||||
return ImmutableList.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object)} over more contrived alternatives or alternatives that
|
||||
* don't communicate the immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Note that the replacement of `Collections#singletonList` is incorrect for nullable
|
||||
// elements.
|
||||
static final class ImmutableListOf1<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T e1) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableList.<T>builder().add(e1).build(), singletonList(e1), List.of(e1));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T e1) {
|
||||
return ImmutableList.of(e1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object, Object)} over alternatives that don't communicate the
|
||||
* immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableList.builder()` usages.
|
||||
static final class ImmutableListOf2<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T e1, T e2) {
|
||||
return List.of(e1, e2);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T e1, T e2) {
|
||||
return ImmutableList.of(e1, e2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object, Object, Object)} over alternatives that don't
|
||||
* communicate the immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableList.builder()` usages.
|
||||
static final class ImmutableListOf3<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T e1, T e2, T e3) {
|
||||
return List.of(e1, e2, e3);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T e1, T e2, T e3) {
|
||||
return ImmutableList.of(e1, e2, e3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object, Object, Object, Object)} over alternatives that don't
|
||||
* communicate the immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableList.builder()` usages.
|
||||
static final class ImmutableListOf4<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T e1, T e2, T e3, T e4) {
|
||||
return List.of(e1, e2, e3, e4);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T e1, T e2, T e3, T e4) {
|
||||
return ImmutableList.of(e1, e2, e3, e4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableList#of(Object, Object, Object, Object, Object)} over alternatives that
|
||||
* don't communicate the immutability of the resulting list at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableList.builder()` usages.
|
||||
static final class ImmutableListOf5<T> {
|
||||
@BeforeTemplate
|
||||
List<T> before(T e1, T e2, T e3, T e4, T e5) {
|
||||
return List.of(e1, e2, e3, e4, e5);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableList<T> after(T e1, T e2, T e3, T e4, T e5) {
|
||||
return ImmutableList.of(e1, e2, e3, e4, e5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableMap.toImmutableMap;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Collections.emptyMap;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import static java.util.function.Function.identity;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -14,7 +16,6 @@ import com.google.errorprone.refaster.annotation.MayOptionallyUse;
|
||||
import com.google.errorprone.refaster.annotation.Placeholder;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -40,41 +41,6 @@ final class ImmutableMapTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableMap#of()} over more contrived alternatives. */
|
||||
static final class EmptyImmutableMap<K, V> {
|
||||
@BeforeTemplate
|
||||
ImmutableMap<K, V> before() {
|
||||
return ImmutableMap.<K, V>builder().build();
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after() {
|
||||
return ImmutableMap.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object)} over more contrived alternatives and
|
||||
* alternatives that don't communicate the immutability of the resulting map at the type level..
|
||||
*/
|
||||
// XXX: One can define variants for more than one key-value pair, but at some point the builder
|
||||
// actually produces nicer code. So it's not clear we should add Refaster templates for those
|
||||
// variants.
|
||||
// XXX: Note that the `singletonMap` rewrite rule is incorrect for nullable elements.
|
||||
static final class PairToImmutableMap<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K key, V value) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableMap.<K, V>builder().put(key, value).build(),
|
||||
Collections.singletonMap(key, value));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K key, V value) {
|
||||
return ImmutableMap.of(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableMap#of(Object, Object)} over more contrived alternatives. */
|
||||
static final class EntryToImmutableMap<K, V> {
|
||||
@BeforeTemplate
|
||||
@@ -178,7 +144,7 @@ final class ImmutableMapTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableMap<K, V> after(Stream<E> stream) {
|
||||
return stream.collect(toImmutableMap(e -> keyFunction(e), e -> valueFunction(e)));
|
||||
}
|
||||
@@ -242,16 +208,108 @@ final class ImmutableMapTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily copy an {@link ImmutableMap}. */
|
||||
static final class ImmutableMapCopyOfImmutableMap<K, V> {
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of()} over more contrived alternatives or alternatives that don't
|
||||
* communicate the immutability of the resulting map at the type level.
|
||||
*/
|
||||
static final class ImmutableMapOf<K, V> {
|
||||
@BeforeTemplate
|
||||
ImmutableMap<K, V> before(ImmutableMap<K, V> map) {
|
||||
return ImmutableMap.copyOf(map);
|
||||
Map<K, V> before() {
|
||||
return Refaster.anyOf(ImmutableMap.<K, V>builder().build(), emptyMap(), Map.of());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(ImmutableMap<K, V> map) {
|
||||
return map;
|
||||
ImmutableMap<K, V> after() {
|
||||
return ImmutableMap.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object)} over more contrived alternatives or alternatives
|
||||
* that don't communicate the immutability of the resulting map at the type level.
|
||||
*/
|
||||
// XXX: Note that the replacement of `Collections#singletonMap` is incorrect for nullable
|
||||
// elements.
|
||||
static final class ImmutableMapOf1<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K k1, V v1) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableMap.<K, V>builder().put(k1, v1).build(), singletonMap(k1, v1), Map.of(k1, v1));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K k1, V v1) {
|
||||
return ImmutableMap.of(k1, v1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object, Object, Object)} over alternatives that don't
|
||||
* communicate the immutability of the resulting map at the type level.
|
||||
*/
|
||||
// XXX: Also rewrite the `ImmutableMap.builder()` variant?
|
||||
static final class ImmutableMapOf2<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K k1, V v1, K k2, V v2) {
|
||||
return Map.of(k1, v1, k2, v2);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K k1, V v1, K k2, V v2) {
|
||||
return ImmutableMap.of(k1, v1, k2, v2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object, Object, Object, Object, Object)} over
|
||||
* alternatives that don't communicate the immutability of the resulting map at the type level.
|
||||
*/
|
||||
// XXX: Also rewrite the `ImmutableMap.builder()` variant?
|
||||
static final class ImmutableMapOf3<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K k1, V v1, K k2, V v2, K k3, V v3) {
|
||||
return Map.of(k1, v1, k2, v2, k3, v3);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K k1, V v1, K k2, V v2, K k3, V v3) {
|
||||
return ImmutableMap.of(k1, v1, k2, v2, k3, v3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object, Object, Object, Object, Object, Object, Object)}
|
||||
* over alternatives that don't communicate the immutability of the resulting map at the type
|
||||
* level.
|
||||
*/
|
||||
// XXX: Also rewrite the `ImmutableMap.builder()` variant?
|
||||
static final class ImmutableMapOf4<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
|
||||
return Map.of(k1, v1, k2, v2, k3, v3, k4, v4);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
|
||||
return ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableMap#of(Object, Object, Object, Object, Object, Object, Object, Object,
|
||||
* Object, Object)} over alternatives that don't communicate the immutability of the resulting map
|
||||
* at the type level.
|
||||
*/
|
||||
// XXX: Also rewrite the `ImmutableMap.builder()` variant?
|
||||
static final class ImmutableMapOf5<K, V> {
|
||||
@BeforeTemplate
|
||||
Map<K, V> before(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
|
||||
return Map.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMap<K, V> after(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
|
||||
return ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableMultiset.toImmutableMultiset;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
import com.google.common.collect.ImmutableMultiset;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -92,27 +92,13 @@ final class ImmutableMultisetTemplates {
|
||||
ImmutableMultiset<T> before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableMultiset.copyOf(stream.iterator()),
|
||||
ImmutableMultiset.copyOf(stream::iterator),
|
||||
stream.collect(collectingAndThen(toList(), ImmutableMultiset::copyOf)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableMultiset<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableMultiset());
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily copy an {@link ImmutableMultiset}. */
|
||||
static final class ImmutableMultisetCopyOfImmutableMultiset<T> {
|
||||
@BeforeTemplate
|
||||
ImmutableMultiset<T> before(ImmutableMultiset<T> multiset) {
|
||||
return ImmutableMultiset.copyOf(multiset);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableMultiset<T> after(ImmutableMultiset<T> multiset) {
|
||||
return multiset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableSetMultimap.flatteningToImmutableSetMultimap;
|
||||
import static com.google.common.collect.ImmutableSetMultimap.toImmutableSetMultimap;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
|
||||
import com.google.common.collect.ImmutableSetMultimap;
|
||||
import com.google.common.collect.ListMultimap;
|
||||
@@ -10,7 +11,6 @@ import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.SetMultimap;
|
||||
import com.google.common.collect.SortedSetMultimap;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -138,7 +138,7 @@ final class ImmutableSetMultimapTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableSetMultimap<K, V> after(Stream<E> stream) {
|
||||
return stream.collect(toImmutableSetMultimap(e -> keyFunction(e), e -> valueFunction(e)));
|
||||
}
|
||||
@@ -162,7 +162,7 @@ final class ImmutableSetMultimapTemplates {
|
||||
@AfterTemplate
|
||||
ImmutableSetMultimap<K, V2> after(Multimap<K, V1> multimap) {
|
||||
return ImmutableSetMultimap.copyOf(
|
||||
Multimaps.transformValues(multimap, v -> valueTransformation(v)));
|
||||
Multimaps.transformValues(multimap, e -> valueTransformation(e)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,17 +215,4 @@ final class ImmutableSetMultimapTemplates {
|
||||
return ImmutableSetMultimap.copyOf(Multimaps.transformValues(multimap, transformation));
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily copy an {@link ImmutableSetMultimap}. */
|
||||
static final class ImmutableSetMultimapCopyOfImmutableSetMultimap<K, V> {
|
||||
@BeforeTemplate
|
||||
ImmutableSetMultimap<K, V> before(ImmutableSetMultimap<K, V> multimap) {
|
||||
return ImmutableSetMultimap.copyOf(multimap);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSetMultimap<K, V> after(ImmutableSetMultimap<K, V> multimap) {
|
||||
return multimap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableSet.toImmutableSet;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Collections.emptySet;
|
||||
import static java.util.Collections.singleton;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
@@ -8,14 +11,12 @@ import static java.util.stream.Collectors.toSet;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets.SetView;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
@@ -39,37 +40,6 @@ final class ImmutableSetTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableSet#of()} over more contrived alternatives. */
|
||||
static final class EmptyImmutableSet<T> {
|
||||
@BeforeTemplate
|
||||
ImmutableSet<T> before() {
|
||||
return Refaster.anyOf(
|
||||
ImmutableSet.<T>builder().build(), Stream.<T>empty().collect(toImmutableSet()));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after() {
|
||||
return ImmutableSet.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object)} over alternatives that don't communicate the
|
||||
* immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Note that this rewrite rule is incorrect for nullable elements.
|
||||
static final class SingletonImmutableSet<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T element) {
|
||||
return Collections.singleton(element);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T element) {
|
||||
return ImmutableSet.of(element);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link ImmutableSet#copyOf(Iterable)} and variants over more contrived alternatives. */
|
||||
static final class IterableToImmutableSet<T> {
|
||||
@BeforeTemplate
|
||||
@@ -114,32 +84,18 @@ final class ImmutableSetTemplates {
|
||||
ImmutableSet<T> before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableSet.copyOf(stream.iterator()),
|
||||
ImmutableSet.copyOf(stream::iterator),
|
||||
stream.distinct().collect(toImmutableSet()),
|
||||
stream.collect(collectingAndThen(toList(), ImmutableSet::copyOf)),
|
||||
stream.collect(collectingAndThen(toSet(), ImmutableSet::copyOf)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableSet<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableSet());
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily copy an {@link ImmutableSet}. */
|
||||
static final class ImmutableSetCopyOfImmutableSet<T> {
|
||||
@BeforeTemplate
|
||||
ImmutableSet<T> before(ImmutableSet<T> set) {
|
||||
return ImmutableSet.copyOf(set);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(ImmutableSet<T> set) {
|
||||
return set;
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link SetView#immutableCopy()} over the more verbose alternative. */
|
||||
static final class ImmutableSetCopyOfSetView<T> {
|
||||
@BeforeTemplate
|
||||
@@ -152,4 +108,115 @@ final class ImmutableSetTemplates {
|
||||
return set.immutableCopy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of()} over more contrived alternatives or alternatives that don't
|
||||
* communicate the immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: The `Stream` variant may be too contrived to warrant inclusion. Review its usage if/when
|
||||
// this and similar Refaster templates are replaced with an Error Prone check.
|
||||
static final class ImmutableSetOf<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before() {
|
||||
return Refaster.anyOf(
|
||||
ImmutableSet.<T>builder().build(),
|
||||
Stream.<T>empty().collect(toImmutableSet()),
|
||||
emptySet(),
|
||||
Set.of());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after() {
|
||||
return ImmutableSet.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object)} over more contrived alternatives or alternatives that
|
||||
* don't communicate the immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Note that the replacement of `Collections#singleton` is incorrect for nullable elements.
|
||||
static final class ImmutableSetOf1<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T e1) {
|
||||
return Refaster.anyOf(ImmutableSet.<T>builder().add(e1).build(), singleton(e1), Set.of(e1));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T e1) {
|
||||
return ImmutableSet.of(e1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object, Object)} over alternatives that don't communicate the
|
||||
* immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableSet.builder()` usages.
|
||||
static final class ImmutableSetOf2<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T e1, T e2) {
|
||||
return Set.of(e1, e2);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T e1, T e2) {
|
||||
return ImmutableSet.of(e1, e2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object, Object, Object)} over alternatives that don't communicate
|
||||
* the immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableSet.builder()` usages.
|
||||
static final class ImmutableSetOf3<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T e1, T e2, T e3) {
|
||||
return Set.of(e1, e2, e3);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T e1, T e2, T e3) {
|
||||
return ImmutableSet.of(e1, e2, e3);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object, Object, Object, Object)} over alternatives that don't
|
||||
* communicate the immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableSet.builder()` usages.
|
||||
static final class ImmutableSetOf4<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T e1, T e2, T e3, T e4) {
|
||||
return Set.of(e1, e2, e3, e4);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T e1, T e2, T e3, T e4) {
|
||||
return ImmutableSet.of(e1, e2, e3, e4);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link ImmutableSet#of(Object, Object, Object, Object, Object)} over alternatives that
|
||||
* don't communicate the immutability of the resulting set at the type level.
|
||||
*/
|
||||
// XXX: Consider writing an Error Prone check which also flags straightforward
|
||||
// `ImmutableSet.builder()` usages.
|
||||
static final class ImmutableSetOf5<T> {
|
||||
@BeforeTemplate
|
||||
Set<T> before(T e1, T e2, T e3, T e4, T e5) {
|
||||
return Set.of(e1, e2, e3, e4, e5);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ImmutableSet<T> after(T e1, T e2, T e3, T e4, T e5) {
|
||||
return ImmutableSet.of(e1, e2, e3, e4, e5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableSortedMultiset.toImmutableSortedMultiset;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
@@ -8,7 +9,6 @@ import static java.util.stream.Collectors.toList;
|
||||
import com.google.common.collect.ImmutableMultiset;
|
||||
import com.google.common.collect.ImmutableSortedMultiset;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -136,12 +136,11 @@ final class ImmutableSortedMultisetTemplates {
|
||||
ImmutableSortedMultiset<T> before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableSortedMultiset.copyOf(stream.iterator()),
|
||||
ImmutableSortedMultiset.copyOf(stream::iterator),
|
||||
stream.collect(collectingAndThen(toList(), ImmutableSortedMultiset::copyOf)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableSortedMultiset<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableSortedMultiset(naturalOrder()));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
@@ -8,7 +9,6 @@ import static java.util.stream.Collectors.toList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSortedSet;
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -136,12 +136,11 @@ final class ImmutableSortedSetTemplates {
|
||||
ImmutableSortedSet<T> before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
ImmutableSortedSet.copyOf(stream.iterator()),
|
||||
ImmutableSortedSet.copyOf(stream::iterator),
|
||||
stream.collect(collectingAndThen(toList(), ImmutableSortedSet::copyOf)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
ImmutableSortedSet<T> after(Stream<T> stream) {
|
||||
return stream.collect(toImmutableSortedSet(naturalOrder()));
|
||||
}
|
||||
|
||||
@@ -246,10 +246,7 @@ final class IntStreamTemplates {
|
||||
static final class IntStreamAllMatch {
|
||||
@BeforeTemplate
|
||||
boolean before(IntStream stream, IntPredicate predicate) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(predicate.negate()),
|
||||
!stream.anyMatch(predicate.negate()),
|
||||
stream.filter(predicate.negate()).findAny().isEmpty());
|
||||
return stream.noneMatch(predicate.negate());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -264,10 +261,7 @@ final class IntStreamTemplates {
|
||||
|
||||
@BeforeTemplate
|
||||
boolean before(IntStream stream) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(e -> !test(e)),
|
||||
!stream.anyMatch(e -> !test(e)),
|
||||
stream.filter(e -> !test(e)).findAny().isEmpty());
|
||||
return stream.noneMatch(e -> !test(e));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.Repeated;
|
||||
@@ -21,7 +21,7 @@ final class JUnitTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Arguments after(@Repeated T objects) {
|
||||
return arguments(objects);
|
||||
}
|
||||
|
||||
@@ -246,10 +246,7 @@ final class LongStreamTemplates {
|
||||
static final class LongStreamAllMatch {
|
||||
@BeforeTemplate
|
||||
boolean before(LongStream stream, LongPredicate predicate) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(predicate.negate()),
|
||||
!stream.anyMatch(predicate.negate()),
|
||||
stream.filter(predicate.negate()).findAny().isEmpty());
|
||||
return stream.noneMatch(predicate.negate());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -264,10 +261,7 @@ final class LongStreamTemplates {
|
||||
|
||||
@BeforeTemplate
|
||||
boolean before(LongStream stream) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(e -> !test(e)),
|
||||
!stream.anyMatch(e -> !test(e)),
|
||||
stream.filter(e -> !test(e)).findAny().isEmpty());
|
||||
return stream.noneMatch(e -> !test(e));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Comparator.comparing;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.Map.Entry.comparingByKey;
|
||||
import static java.util.Map.Entry.comparingByValue;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -42,15 +47,13 @@ final class MapEntryTemplates {
|
||||
static final class MapEntryComparingByKey<K extends Comparable<? super K>, V> {
|
||||
@BeforeTemplate
|
||||
Comparator<Map.Entry<K, V>> before() {
|
||||
return Refaster.anyOf(
|
||||
Comparator.comparing(Map.Entry::getKey),
|
||||
Map.Entry.comparingByKey(Comparator.naturalOrder()));
|
||||
return Refaster.anyOf(comparing(Map.Entry::getKey), comparingByKey(naturalOrder()));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<Map.Entry<K, V>> after() {
|
||||
return Map.Entry.comparingByKey();
|
||||
return comparingByKey();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,13 +61,13 @@ final class MapEntryTemplates {
|
||||
static final class MapEntryComparingByKeyWithCustomComparator<K, V> {
|
||||
@BeforeTemplate
|
||||
Comparator<Map.Entry<K, V>> before(Comparator<? super K> cmp) {
|
||||
return Comparator.comparing(Map.Entry::getKey, cmp);
|
||||
return comparing(Map.Entry::getKey, cmp);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<Map.Entry<K, V>> after(Comparator<? super K> cmp) {
|
||||
return Map.Entry.comparingByKey(cmp);
|
||||
return comparingByKey(cmp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,15 +76,13 @@ final class MapEntryTemplates {
|
||||
static final class MapEntryComparingByValue<K, V extends Comparable<? super V>> {
|
||||
@BeforeTemplate
|
||||
Comparator<Map.Entry<K, V>> before() {
|
||||
return Refaster.anyOf(
|
||||
Comparator.comparing(Map.Entry::getValue),
|
||||
Map.Entry.comparingByValue(Comparator.naturalOrder()));
|
||||
return Refaster.anyOf(comparing(Map.Entry::getValue), comparingByValue(naturalOrder()));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<Map.Entry<K, V>> after() {
|
||||
return Map.Entry.comparingByValue();
|
||||
return comparingByValue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +90,13 @@ final class MapEntryTemplates {
|
||||
static final class MapEntryComparingByValueWithCustomComparator<K, V> {
|
||||
@BeforeTemplate
|
||||
Comparator<Map.Entry<K, V>> before(Comparator<? super V> cmp) {
|
||||
return Comparator.comparing(Map.Entry::getValue, cmp);
|
||||
return comparing(Map.Entry::getValue, cmp);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Comparator<Map.Entry<K, V>> after(Comparator<? super V> cmp) {
|
||||
return Map.Entry.comparingByValue(cmp);
|
||||
return comparingByValue(cmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
@@ -26,7 +26,7 @@ final class MockitoTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
VerificationMode after() {
|
||||
return never();
|
||||
}
|
||||
@@ -43,7 +43,7 @@ final class MockitoTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
T after(T mock) {
|
||||
return verify(mock);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Objects.requireNonNullElse;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
@@ -22,9 +24,9 @@ final class NullTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
T after(T first, T second) {
|
||||
return Objects.requireNonNullElse(first, second);
|
||||
return requireNonNullElse(first, second);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -14,17 +15,18 @@ import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/** Refaster templates related to expressions dealing with {@link Optional}s. */
|
||||
final class OptionalTemplates {
|
||||
private OptionalTemplates() {}
|
||||
|
||||
static final class OptionalOfNullable<T> {
|
||||
@BeforeTemplate
|
||||
// XXX: Refaster should be smart enough to also rewrite occurrences in which there are
|
||||
// parentheses around the null check, but that's currently not the case. Try to fix that.
|
||||
// XXX: This is a special case of `TernaryOperatorOptionalNegativeFiltering`.
|
||||
Optional<T> before(T object) {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("TernaryOperatorOptionalNegativeFiltering" /* Special case. */)
|
||||
Optional<T> before(@Nullable T object) {
|
||||
return object == null ? Optional.empty() : Optional.of(object);
|
||||
}
|
||||
|
||||
@@ -91,19 +93,6 @@ final class OptionalTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Optional#stream()} over the Guava alternative. */
|
||||
static final class OptionalToStream<T> {
|
||||
@BeforeTemplate
|
||||
Stream<T> before(Optional<T> optional) {
|
||||
return Streams.stream(optional);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Stream<T> after(Optional<T> optional) {
|
||||
return optional.stream();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't use the ternary operator to extract the first element of a possibly-empty {@link
|
||||
* Iterator} as an {@link Optional}.
|
||||
@@ -115,7 +104,7 @@ final class OptionalTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Optional<T> after(Iterator<T> it) {
|
||||
return Streams.stream(it).findFirst();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.common.collect.MoreCollectors.toOptional;
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.common.collect.MoreCollectors;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -77,7 +78,7 @@ final class ReactorTemplates {
|
||||
static final class MonoErrorSupplier<T, E extends Throwable> {
|
||||
@BeforeTemplate
|
||||
Mono<T> before(Supplier<E> supplier) {
|
||||
return Refaster.anyOf(Mono.error(supplier::get), Mono.error(() -> supplier.get()));
|
||||
return Mono.error(() -> supplier.get());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -94,7 +95,7 @@ final class ReactorTemplates {
|
||||
static final class FluxErrorSupplier<T, E extends Throwable> {
|
||||
@BeforeTemplate
|
||||
Flux<T> before(Supplier<E> supplier) {
|
||||
return Refaster.anyOf(Flux.error(supplier::get), Flux.error(() -> supplier.get()));
|
||||
return Flux.error(() -> supplier.get());
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -142,6 +143,35 @@ final class ReactorTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Flux#concatMap(Function)} over more contrived alternatives. */
|
||||
static final class FluxConcatMap<T, S> {
|
||||
@BeforeTemplate
|
||||
Flux<S> before(Flux<T> flux, Function<? super T, ? extends Publisher<? extends S>> function) {
|
||||
return Refaster.anyOf(flux.flatMap(function, 1), flux.flatMapSequential(function, 1));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Flux<S> after(Flux<T> flux, Function<? super T, ? extends Publisher<? extends S>> function) {
|
||||
return flux.concatMap(function);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer {@link Flux#concatMapIterable(Function)} over {@link Flux#concatMapIterable(Function)},
|
||||
* as the former has equivalent semantics but a clearer name.
|
||||
*/
|
||||
static final class FluxConcatMapIterable<T, S> {
|
||||
@BeforeTemplate
|
||||
Flux<S> before(Flux<T> flux, Function<? super T, ? extends Iterable<? extends S>> function) {
|
||||
return flux.flatMapIterable(function);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Flux<S> after(Flux<T> flux, Function<? super T, ? extends Iterable<? extends S>> function) {
|
||||
return flux.concatMapIterable(function);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't use {@link Mono#flatMapMany(Function)} to implicitly convert a {@link Mono} to a {@link
|
||||
* Flux}.
|
||||
@@ -161,6 +191,19 @@ final class ReactorTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Mono#flux()}} over more contrived alternatives. */
|
||||
static final class MonoFlux<T> {
|
||||
@BeforeTemplate
|
||||
Flux<T> before(Mono<T> mono) {
|
||||
return Flux.concat(mono);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Flux<T> after(Mono<T> mono) {
|
||||
return mono.flux();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefer a collection using {@link MoreCollectors#toOptional()} over more contrived alternatives.
|
||||
*/
|
||||
@@ -175,7 +218,7 @@ final class ReactorTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Mono<Optional<T>> after(Mono<T> mono) {
|
||||
return mono.flux().collect(toOptional());
|
||||
}
|
||||
@@ -194,6 +237,32 @@ final class ReactorTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Mono#as(Function)} when creating a {@link StepVerifier}. */
|
||||
static final class StepVerifierFromMono<T> {
|
||||
@BeforeTemplate
|
||||
StepVerifier.FirstStep<? extends T> before(Mono<T> mono) {
|
||||
return StepVerifier.create(mono);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
StepVerifier.FirstStep<? extends T> after(Mono<T> mono) {
|
||||
return mono.as(StepVerifier::create);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Flux#as(Function)} when creating a {@link StepVerifier}. */
|
||||
static final class StepVerifierFromFlux<T> {
|
||||
@BeforeTemplate
|
||||
StepVerifier.FirstStep<? extends T> before(Flux<T> flux) {
|
||||
return StepVerifier.create(flux);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
StepVerifier.FirstStep<? extends T> after(Flux<T> flux) {
|
||||
return flux.as(StepVerifier::create);
|
||||
}
|
||||
}
|
||||
|
||||
/** Don't unnecessarily call {@link StepVerifier.Step#expectNext(Object[])}. */
|
||||
static final class StepVerifierStepExpectNextEmpty<T> {
|
||||
@BeforeTemplate
|
||||
@@ -252,7 +321,9 @@ final class ReactorTemplates {
|
||||
static final class StepVerifierLastStepVerifyErrorClass<T extends Throwable> {
|
||||
@BeforeTemplate
|
||||
Duration before(StepVerifier.LastStep step, Class<T> clazz) {
|
||||
return step.expectError(clazz).verify();
|
||||
return Refaster.anyOf(
|
||||
step.expectError(clazz).verify(),
|
||||
step.verifyErrorSatisfies(t -> assertThat(t).isInstanceOf(clazz)));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -41,11 +41,9 @@ final class RxJava2AdapterTemplates {
|
||||
@BeforeTemplate
|
||||
Publisher<T> before(Flowable<T> flowable) {
|
||||
return Refaster.anyOf(
|
||||
Flux.from(flowable),
|
||||
flowable.compose(Flux::from),
|
||||
flowable.to(Flux::from),
|
||||
flowable.as(Flux::from),
|
||||
RxJava2Adapter.flowableToFlux(flowable),
|
||||
flowable.compose(RxJava2Adapter::flowableToFlux),
|
||||
flowable.to(RxJava2Adapter::flowableToFlux));
|
||||
}
|
||||
@@ -67,7 +65,6 @@ final class RxJava2AdapterTemplates {
|
||||
Flowable.fromPublisher(flux),
|
||||
flux.transform(Flowable::fromPublisher),
|
||||
flux.as(Flowable::fromPublisher),
|
||||
RxJava2Adapter.fluxToFlowable(flux),
|
||||
flux.transform(RxJava2Adapter::fluxToFlowable));
|
||||
}
|
||||
|
||||
@@ -140,7 +137,6 @@ final class RxJava2AdapterTemplates {
|
||||
Flowable.fromPublisher(mono),
|
||||
mono.transform(Flowable::fromPublisher),
|
||||
mono.as(Flowable::fromPublisher),
|
||||
RxJava2Adapter.monoToFlowable(mono),
|
||||
mono.transform(RxJava2Adapter::monoToFlowable));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static java.util.Comparator.naturalOrder;
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
import static java.util.function.Predicate.not;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
import com.google.common.collect.Streams;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
@@ -18,12 +19,31 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** Refaster templates related to expressions dealing with {@link Stream}s. */
|
||||
final class StreamTemplates {
|
||||
private StreamTemplates() {}
|
||||
|
||||
/**
|
||||
* Prefer {@link Collectors#joining()} over {@link Collectors#joining(CharSequence)} with an empty
|
||||
* delimiter string.
|
||||
*/
|
||||
static final class Joining {
|
||||
@BeforeTemplate
|
||||
Collector<CharSequence, ?, String> before() {
|
||||
return joining("");
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Collector<CharSequence, ?, String> after() {
|
||||
return joining();
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Stream#empty()} over less clear alternatives. */
|
||||
static final class EmptyStream<T> {
|
||||
@BeforeTemplate
|
||||
@@ -148,6 +168,8 @@ final class StreamTemplates {
|
||||
*/
|
||||
// XXX: Consider whether to have a similar rule for `.findAny()`. For parallel streams it
|
||||
// wouldn't be quite the same....
|
||||
// XXX: This change is not equivalent for `null`-returning functions, as the original code throws
|
||||
// an NPE if the first element is `null`, while the latter yields an empty `Optional`.
|
||||
static final class StreamMapFirst<T, S> {
|
||||
@BeforeTemplate
|
||||
Optional<S> before(Stream<T> stream, Function<? super T, S> function) {
|
||||
@@ -214,7 +236,7 @@ final class StreamTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Optional<T> after(Stream<T> stream) {
|
||||
return stream.min(naturalOrder());
|
||||
}
|
||||
@@ -240,7 +262,7 @@ final class StreamTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
Optional<T> after(Stream<T> stream) {
|
||||
return stream.max(naturalOrder());
|
||||
}
|
||||
@@ -294,10 +316,7 @@ final class StreamTemplates {
|
||||
static final class StreamAllMatch<T> {
|
||||
@BeforeTemplate
|
||||
boolean before(Stream<T> stream, Predicate<? super T> predicate) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(Refaster.anyOf(not(predicate), predicate.negate())),
|
||||
!stream.anyMatch(Refaster.anyOf(not(predicate), predicate.negate())),
|
||||
stream.filter(Refaster.anyOf(not(predicate), predicate.negate())).findAny().isEmpty());
|
||||
return stream.noneMatch(Refaster.anyOf(not(predicate), predicate.negate()));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@@ -312,10 +331,7 @@ final class StreamTemplates {
|
||||
|
||||
@BeforeTemplate
|
||||
boolean before(Stream<T> stream) {
|
||||
return Refaster.anyOf(
|
||||
stream.noneMatch(e -> !test(e)),
|
||||
!stream.anyMatch(e -> !test(e)),
|
||||
stream.filter(e -> !test(e)).findAny().isEmpty());
|
||||
return stream.noneMatch(e -> !test(e));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
@@ -10,10 +11,10 @@ import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.AlsoNegation;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/** Refaster templates related to expressions dealing with {@link String}s. */
|
||||
// XXX: Should we prefer `s -> !s.isEmpty()` or `not(String::isEmpty)`?
|
||||
@@ -37,7 +38,7 @@ final class StringTemplates {
|
||||
/** Prefer {@link Strings#isNullOrEmpty(String)} over the more verbose alternative. */
|
||||
static final class StringIsNullOrEmpty {
|
||||
@BeforeTemplate
|
||||
boolean before(String str) {
|
||||
boolean before(@Nullable String str) {
|
||||
return str == null || str.isEmpty();
|
||||
}
|
||||
|
||||
@@ -122,7 +123,7 @@ final class StringTemplates {
|
||||
static final class Utf8EncodedLength {
|
||||
@BeforeTemplate
|
||||
int before(String str) {
|
||||
return str.getBytes(StandardCharsets.UTF_8).length;
|
||||
return str.getBytes(UTF_8).length;
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static com.google.errorprone.refaster.ImportPolicy.STATIC_IMPORT_ALWAYS;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
@@ -16,7 +17,7 @@ import static org.testng.Assert.assertThrows;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.errorprone.refaster.ImportPolicy;
|
||||
import com.google.errorprone.annotations.DoNotCall;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import com.google.errorprone.refaster.annotation.UseImportPolicy;
|
||||
@@ -81,6 +82,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@DoNotCall
|
||||
void after() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
@@ -94,7 +96,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(String message) {
|
||||
fail(message);
|
||||
}
|
||||
@@ -108,7 +110,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(String message, Throwable throwable) {
|
||||
fail(message, throwable);
|
||||
}
|
||||
@@ -121,7 +123,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(boolean condition) {
|
||||
assertThat(condition).isTrue();
|
||||
}
|
||||
@@ -134,7 +136,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(boolean condition, String message) {
|
||||
assertThat(condition).withFailMessage(message).isTrue();
|
||||
}
|
||||
@@ -147,7 +149,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(boolean condition) {
|
||||
assertThat(condition).isFalse();
|
||||
}
|
||||
@@ -160,7 +162,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(boolean condition, String message) {
|
||||
assertThat(condition).withFailMessage(message).isFalse();
|
||||
}
|
||||
@@ -173,7 +175,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object object) {
|
||||
assertThat(object).isNull();
|
||||
}
|
||||
@@ -186,7 +188,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object object, String message) {
|
||||
assertThat(object).withFailMessage(message).isNull();
|
||||
}
|
||||
@@ -199,7 +201,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object object) {
|
||||
assertThat(object).isNotNull();
|
||||
}
|
||||
@@ -212,7 +214,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object object, String message) {
|
||||
assertThat(object).withFailMessage(message).isNotNull();
|
||||
}
|
||||
@@ -225,7 +227,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected) {
|
||||
assertThat(actual).isSameAs(expected);
|
||||
}
|
||||
@@ -238,7 +240,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).isSameAs(expected);
|
||||
}
|
||||
@@ -251,7 +253,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected) {
|
||||
assertThat(actual).isNotSameAs(expected);
|
||||
}
|
||||
@@ -264,7 +266,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).isNotSameAs(expected);
|
||||
}
|
||||
@@ -327,7 +329,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected) {
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
@@ -390,7 +392,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).isEqualTo(expected);
|
||||
}
|
||||
@@ -403,7 +405,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(float actual, float expected, float delta) {
|
||||
assertThat(actual).isCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -416,7 +418,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(float actual, float expected, float delta, String message) {
|
||||
assertThat(actual).withFailMessage(message).isCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -429,7 +431,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(double actual, double expected, double delta) {
|
||||
assertThat(actual).isCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -442,7 +444,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(double actual, double expected, double delta, String message) {
|
||||
assertThat(actual).withFailMessage(message).isCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -495,7 +497,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object[] actual, Object[] expected) {
|
||||
assertThat(actual).containsExactly(expected);
|
||||
}
|
||||
@@ -548,7 +550,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object[] actual, Object[] expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).containsExactly(expected);
|
||||
}
|
||||
@@ -561,7 +563,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object[] actual, Object[] expected) {
|
||||
assertThat(actual).containsExactlyInAnyOrder(expected);
|
||||
}
|
||||
@@ -574,7 +576,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object[] actual, Object[] expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).containsExactlyInAnyOrder(expected);
|
||||
}
|
||||
@@ -587,7 +589,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Iterator<S> actual, Iterator<T> expected) {
|
||||
// XXX: This is not `null`-safe.
|
||||
// XXX: The `ImmutableList.copyOf` should actually *not* be imported statically.
|
||||
@@ -602,7 +604,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Iterator<S> actual, Iterator<T> expected, String message) {
|
||||
// XXX: This is not `null`-safe.
|
||||
// XXX: The `ImmutableList.copyOf` should actually *not* be imported statically.
|
||||
@@ -627,7 +629,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Iterable<S> actual, Iterable<T> expected) {
|
||||
assertThat(actual).containsExactlyElementsOf(expected);
|
||||
}
|
||||
@@ -645,7 +647,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Iterable<S> actual, Iterable<T> expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).containsExactlyElementsOf(expected);
|
||||
}
|
||||
@@ -658,7 +660,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Set<S> actual, Set<T> expected) {
|
||||
assertThat(actual).hasSameElementsAs(expected);
|
||||
}
|
||||
@@ -671,7 +673,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
<S, T extends S> void after(Set<S> actual, Set<T> expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).hasSameElementsAs(expected);
|
||||
}
|
||||
@@ -739,7 +741,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected) {
|
||||
assertThat(actual).isNotEqualTo(expected);
|
||||
}
|
||||
@@ -807,7 +809,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(Object actual, Object expected, String message) {
|
||||
assertThat(actual).withFailMessage(message).isNotEqualTo(expected);
|
||||
}
|
||||
@@ -820,7 +822,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(float actual, float expected, float delta) {
|
||||
assertThat(actual).isNotCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -833,7 +835,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(float actual, float expected, float delta, String message) {
|
||||
assertThat(actual).withFailMessage(message).isNotCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -846,7 +848,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(double actual, double expected, double delta) {
|
||||
assertThat(actual).isNotCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -859,7 +861,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(double actual, double expected, double delta, String message) {
|
||||
assertThat(actual).withFailMessage(message).isNotCloseTo(expected, offset(delta));
|
||||
}
|
||||
@@ -872,7 +874,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(ThrowingCallable runnable) {
|
||||
assertThatThrownBy(runnable);
|
||||
}
|
||||
@@ -885,7 +887,7 @@ final class TestNGToAssertJTemplates {
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS)
|
||||
@UseImportPolicy(STATIC_IMPORT_ALWAYS)
|
||||
void after(ThrowingCallable runnable, Class<T> clazz) {
|
||||
assertThatThrownBy(runnable).isInstanceOf(clazz);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static java.time.ZoneOffset.UTC;
|
||||
|
||||
import com.google.errorprone.refaster.Refaster;
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.AlsoNegation;
|
||||
@@ -17,6 +19,7 @@ import java.time.ZoneOffset;
|
||||
import java.time.chrono.ChronoLocalDate;
|
||||
import java.time.chrono.ChronoLocalDateTime;
|
||||
import java.time.chrono.ChronoZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.temporal.TemporalUnit;
|
||||
|
||||
/** Refaster templates related to expressions dealing with time. */
|
||||
@@ -43,30 +46,45 @@ final class TimeTemplates {
|
||||
static final class UtcConstant {
|
||||
@BeforeTemplate
|
||||
ZoneId before() {
|
||||
// `ZoneId.of("Z")` is not listed, because Error Prone flags it out of the box.
|
||||
return Refaster.anyOf(
|
||||
ZoneId.of("GMT"),
|
||||
ZoneId.of("UTC"),
|
||||
ZoneId.of("Z"),
|
||||
ZoneId.of("+0"),
|
||||
ZoneId.of("-0"),
|
||||
ZoneOffset.UTC.normalized(),
|
||||
ZoneId.from(ZoneOffset.UTC));
|
||||
UTC.normalized(),
|
||||
ZoneId.from(UTC));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
ZoneOffset after() {
|
||||
return ZoneOffset.UTC;
|
||||
return UTC;
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Instant#atOffset(ZoneOffset)} over the more verbose alternative. */
|
||||
static final class InstantAtOffset {
|
||||
@BeforeTemplate
|
||||
OffsetDateTime before(Instant instant, ZoneOffset zoneOffset) {
|
||||
return OffsetDateTime.ofInstant(instant, zoneOffset);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
OffsetDateTime after(Instant instant, ZoneOffset zoneOffset) {
|
||||
return instant.atOffset(zoneOffset);
|
||||
}
|
||||
}
|
||||
|
||||
/** Use {@link Clock#systemUTC()} when possible. */
|
||||
static final class UtcClock {
|
||||
@BeforeTemplate
|
||||
@SuppressWarnings("TimeZoneUsage")
|
||||
Clock before() {
|
||||
return Clock.system(ZoneOffset.UTC);
|
||||
return Clock.system(UTC);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
@SuppressWarnings("TimeZoneUsage")
|
||||
Clock after() {
|
||||
return Clock.systemUTC();
|
||||
}
|
||||
@@ -96,8 +114,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(Instant a, Instant b) {
|
||||
return a.isBefore(b);
|
||||
}
|
||||
@@ -113,8 +131,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(Instant a, Instant b) {
|
||||
return a.isAfter(b);
|
||||
}
|
||||
@@ -162,8 +180,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoLocalDate a, ChronoLocalDate b) {
|
||||
return a.isBefore(b);
|
||||
}
|
||||
@@ -179,8 +197,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoLocalDate a, ChronoLocalDate b) {
|
||||
return a.isAfter(b);
|
||||
}
|
||||
@@ -196,8 +214,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoLocalDateTime<?> a, ChronoLocalDateTime<?> b) {
|
||||
return a.isBefore(b);
|
||||
}
|
||||
@@ -213,8 +231,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoLocalDateTime<?> a, ChronoLocalDateTime<?> b) {
|
||||
return a.isAfter(b);
|
||||
}
|
||||
@@ -230,8 +248,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoZonedDateTime<?> a, ChronoZonedDateTime<?> b) {
|
||||
return a.isBefore(b);
|
||||
}
|
||||
@@ -247,8 +265,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(ChronoZonedDateTime<?> a, ChronoZonedDateTime<?> b) {
|
||||
return a.isAfter(b);
|
||||
}
|
||||
@@ -264,8 +282,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) < 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(OffsetDateTime a, OffsetDateTime b) {
|
||||
return a.isBefore(b);
|
||||
}
|
||||
@@ -281,8 +299,8 @@ final class TimeTemplates {
|
||||
return a.compareTo(b) > 0;
|
||||
}
|
||||
|
||||
@AlsoNegation
|
||||
@AfterTemplate
|
||||
@AlsoNegation
|
||||
boolean after(OffsetDateTime a, OffsetDateTime b) {
|
||||
return a.isAfter(b);
|
||||
}
|
||||
@@ -308,8 +326,86 @@ final class TimeTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofDays(long)} over alternative representations. */
|
||||
static final class DurationOfDays {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.DAYS);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofDays(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofHours(long)} over alternative representations. */
|
||||
static final class DurationOfHours {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.HOURS);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofHours(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofMillis(long)} over alternative representations. */
|
||||
static final class DurationOfMillis {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.MILLIS);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofMillis(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofMinutes(long)} over alternative representations. */
|
||||
static final class DurationOfMinutes {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.MINUTES);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofMinutes(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofNanos(long)} over alternative representations. */
|
||||
static final class DurationOfNanos {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.NANOS);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofNanos(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prefer {@link Duration#ofSeconds(long)} over alternative representations. */
|
||||
static final class DurationOfSeconds {
|
||||
@BeforeTemplate
|
||||
Duration before(long amount) {
|
||||
return Duration.of(amount, ChronoUnit.SECONDS);
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
Duration after(long amount) {
|
||||
return Duration.ofSeconds(amount);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't unnecessarily convert two and from milliseconds. (This way nanosecond precision is
|
||||
* Don't unnecessarily convert to and from milliseconds. (This way nanosecond precision is
|
||||
* retained.)
|
||||
*
|
||||
* <p><strong>Warning:</strong> this rewrite rule increases precision!
|
||||
@@ -327,7 +423,7 @@ final class TimeTemplates {
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't unnecessarily convert two and from milliseconds. (This way nanosecond precision is
|
||||
* Don't unnecessarily convert to and from milliseconds. (This way nanosecond precision is
|
||||
* retained.)
|
||||
*
|
||||
* <p><strong>Warning:</strong> this rewrite rule increases precision!
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import static org.springframework.web.reactive.function.BodyInserters.fromValue;
|
||||
|
||||
import com.google.errorprone.refaster.annotation.AfterTemplate;
|
||||
import com.google.errorprone.refaster.annotation.BeforeTemplate;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec;
|
||||
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
|
||||
|
||||
/**
|
||||
* Refaster templates related to expressions dealing with {@link
|
||||
* org.springframework.web.reactive.function.client.WebClient} and related types.
|
||||
*/
|
||||
final class WebClientTemplates {
|
||||
private WebClientTemplates() {}
|
||||
|
||||
/** Prefer {@link RequestBodySpec#bodyValue(Object)} over more contrived alternatives. */
|
||||
static final class BodyValue<T> {
|
||||
@BeforeTemplate
|
||||
RequestHeadersSpec<?> before(RequestBodySpec requestBodySpec, T value) {
|
||||
return requestBodySpec.body(fromValue(value));
|
||||
}
|
||||
|
||||
@BeforeTemplate
|
||||
WebTestClient.RequestHeadersSpec<?> before2(
|
||||
WebTestClient.RequestBodySpec requestBodySpec, T value) {
|
||||
return requestBodySpec.body(fromValue(value));
|
||||
}
|
||||
|
||||
@AfterTemplate
|
||||
RequestHeadersSpec<?> after(RequestBodySpec requestBodySpec, T value) {
|
||||
return requestBodySpec.bodyValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
/** Picnic Refaster templates. */
|
||||
@CheckReturnValue
|
||||
@ParametersAreNonnullByDefault
|
||||
@com.google.errorprone.annotations.CheckReturnValue
|
||||
@javax.annotation.ParametersAreNonnullByDefault
|
||||
package tech.picnic.errorprone.refastertemplates;
|
||||
|
||||
import com.google.errorprone.annotations.CheckReturnValue;
|
||||
import javax.annotation.ParametersAreNonnullByDefault;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.base.Predicates.containsPattern;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
final class AmbiguousJsonCreatorCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(AmbiguousJsonCreatorCheck.class, getClass())
|
||||
.expectErrorMessage(
|
||||
"X",
|
||||
containsPattern("`JsonCreator.Mode` should be set for single-argument creators"));
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(AmbiguousJsonCreatorCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"Container.java",
|
||||
"import com.fasterxml.jackson.annotation.JsonCreator;",
|
||||
"import com.fasterxml.jackson.annotation.JsonValue;",
|
||||
"",
|
||||
"interface Container {",
|
||||
" enum A {",
|
||||
" FOO(1);",
|
||||
"",
|
||||
" private final int i;",
|
||||
"",
|
||||
" A(int i) {",
|
||||
" this.i = i;",
|
||||
" }",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @JsonCreator",
|
||||
" public static A of(int i) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" enum B {",
|
||||
" FOO(1);",
|
||||
"",
|
||||
" private final int i;",
|
||||
"",
|
||||
" B(int i) {",
|
||||
" this.i = i;",
|
||||
" }",
|
||||
"",
|
||||
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)",
|
||||
" public static B of(int i) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" enum C {",
|
||||
" FOO(1, \"s\");",
|
||||
"",
|
||||
" @JsonValue private final int i;",
|
||||
" private final String s;",
|
||||
"",
|
||||
" C(int i, String s) {",
|
||||
" this.i = i;",
|
||||
" this.s = s;",
|
||||
" }",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @JsonCreator",
|
||||
" public static C of(int i) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" enum D {",
|
||||
" FOO(1, \"s\");",
|
||||
"",
|
||||
" private final int i;",
|
||||
" private final String s;",
|
||||
"",
|
||||
" D(int i, String s) {",
|
||||
" this.i = i;",
|
||||
" this.s = s;",
|
||||
" }",
|
||||
"",
|
||||
" @JsonCreator",
|
||||
" public static D of(int i, String s) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" enum E {",
|
||||
" FOO;",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @JsonCreator",
|
||||
" public static E of(String s) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" class F {",
|
||||
" private final String s;",
|
||||
"",
|
||||
" F(String s) {",
|
||||
" this.s = s;",
|
||||
" }",
|
||||
"",
|
||||
" @JsonCreator",
|
||||
" public static F of(String s) {",
|
||||
" return new F(s);",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import com.fasterxml.jackson.annotation.JsonCreator;",
|
||||
"",
|
||||
"enum A {",
|
||||
" FOO;",
|
||||
"",
|
||||
" @JsonCreator",
|
||||
" public static A of(String s) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import com.fasterxml.jackson.annotation.JsonCreator;",
|
||||
"",
|
||||
"enum A {",
|
||||
" FOO;",
|
||||
"",
|
||||
" @JsonCreator(mode = JsonCreator.Mode.DELEGATING)",
|
||||
" public static A of(String s) {",
|
||||
" return FOO;",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class AnnotationAttributeMatcherTest {
|
||||
@Test
|
||||
public void testWithoutListings() {
|
||||
void withoutListings() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(Optional.empty(), ImmutableList.of());
|
||||
assertThat(matcher.matches("foo", "bar")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSingleFullAnnotationWhitelist() {
|
||||
void withSingleFullAnnotationWhitelist() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(Optional.of(ImmutableList.of("foo")), ImmutableList.of());
|
||||
assertThat(matcher.matches("foo", "bar")).isTrue();
|
||||
@@ -24,7 +24,7 @@ public final class AnnotationAttributeMatcherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSingleAnnotationAttributeWhitelist() {
|
||||
void withSingleAnnotationAttributeWhitelist() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(
|
||||
Optional.of(ImmutableList.of("foo#bar")), ImmutableList.of());
|
||||
@@ -34,7 +34,7 @@ public final class AnnotationAttributeMatcherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSingleFullAnnotationBlacklist() {
|
||||
void withSingleFullAnnotationBlacklist() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(Optional.empty(), ImmutableList.of("foo"));
|
||||
assertThat(matcher.matches("foo", "bar")).isFalse();
|
||||
@@ -43,7 +43,7 @@ public final class AnnotationAttributeMatcherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithSingleAnnotationAttributeBlacklist() {
|
||||
void withSingleAnnotationAttributeBlacklist() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(Optional.empty(), ImmutableList.of("foo#bar"));
|
||||
assertThat(matcher.matches("foo", "bar")).isFalse();
|
||||
@@ -52,7 +52,7 @@ public final class AnnotationAttributeMatcherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWithComplicatedConfiguration() {
|
||||
void withComplicatedConfiguration() {
|
||||
AnnotationAttributeMatcher matcher =
|
||||
AnnotationAttributeMatcher.create(
|
||||
Optional.of(ImmutableList.of("foo", "bar", "baz", "baz#1", "baz#2", "quux#1")),
|
||||
|
||||
@@ -9,10 +9,10 @@ public final class AutowiredConstructorCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(AutowiredConstructorCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new AutowiredConstructorCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(AutowiredConstructorCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"Container.java",
|
||||
@@ -62,7 +62,7 @@ public final class AutowiredConstructorCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/Container.java",
|
||||
|
||||
@@ -9,10 +9,10 @@ public final class CanonicalAnnotationSyntaxCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(CanonicalAnnotationSyntaxCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new CanonicalAnnotationSyntaxCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(CanonicalAnnotationSyntaxCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"pkg/A.java",
|
||||
@@ -85,7 +85,7 @@ public final class CanonicalAnnotationSyntaxCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/pkg/A.java",
|
||||
|
||||
@@ -9,10 +9,10 @@ public final class EmptyMethodCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(EmptyMethodCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new EmptyMethodCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(EmptyMethodCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -33,6 +33,10 @@ public final class EmptyMethodCheckTest {
|
||||
" interface F {",
|
||||
" void fun();",
|
||||
" }",
|
||||
"",
|
||||
" final class MyTestClass {",
|
||||
" void helperMethod() {}",
|
||||
" }",
|
||||
"}")
|
||||
.addSourceLines(
|
||||
"B.java",
|
||||
@@ -64,7 +68,7 @@ public final class EmptyMethodCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
final class ExplicitEnumOrderingCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(ExplicitEnumOrderingCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void Identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import static java.lang.annotation.RetentionPolicy.SOURCE;",
|
||||
"import static java.lang.annotation.RetentionPolicy.CLASS;",
|
||||
"import static java.lang.annotation.RetentionPolicy.RUNTIME;",
|
||||
"import static java.time.chrono.IsoEra.BCE;",
|
||||
"import static java.time.chrono.IsoEra.CE;",
|
||||
"",
|
||||
"import com.google.common.collect.Ordering;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import java.lang.annotation.RetentionPolicy;",
|
||||
"import java.time.chrono.IsoEra;",
|
||||
"",
|
||||
"class A {",
|
||||
" {",
|
||||
" // The `List`-accepting overload is currently ignored.",
|
||||
" Ordering.explicit(ImmutableList.of(RetentionPolicy.SOURCE, RetentionPolicy.CLASS));",
|
||||
"",
|
||||
" Ordering.explicit(IsoEra.BCE, IsoEra.CE);",
|
||||
" // BUG: Diagnostic contains: IsoEra.CE",
|
||||
" Ordering.explicit(IsoEra.BCE);",
|
||||
" // BUG: Diagnostic contains: IsoEra.BCE",
|
||||
" Ordering.explicit(IsoEra.CE);",
|
||||
"",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(RetentionPolicy.CLASS);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(RetentionPolicy.RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.CLASS);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE",
|
||||
" Ordering.explicit(RetentionPolicy.CLASS, RetentionPolicy.RUNTIME);",
|
||||
"",
|
||||
" Ordering.explicit(BCE, CE);",
|
||||
" // BUG: Diagnostic contains: IsoEra.CE",
|
||||
" Ordering.explicit(BCE);",
|
||||
" // BUG: Diagnostic contains: IsoEra.BCE",
|
||||
" Ordering.explicit(CE);",
|
||||
"",
|
||||
" Ordering.explicit(SOURCE, CLASS, RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS, RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(SOURCE);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(CLASS);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(SOURCE, CLASS);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(SOURCE, RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE",
|
||||
" Ordering.explicit(CLASS, RUNTIME);",
|
||||
"",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE, BCE, RetentionPolicy.CLASS, CE, RUNTIME);",
|
||||
" Ordering.explicit(SOURCE, IsoEra.BCE, CLASS, IsoEra.CE, RetentionPolicy.RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(RetentionPolicy.SOURCE, BCE, CE, RUNTIME);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.CLASS",
|
||||
" Ordering.explicit(IsoEra.BCE, SOURCE, IsoEra.CE, RetentionPolicy.RUNTIME);",
|
||||
" // BUG: Diagnostic contains: IsoEra.CE, RetentionPolicy.RUNTIME",
|
||||
" Ordering.explicit(IsoEra.BCE, SOURCE, RetentionPolicy.CLASS);",
|
||||
" // BUG: Diagnostic contains: RetentionPolicy.SOURCE, IsoEra.BCE",
|
||||
" Ordering.explicit(CLASS, RUNTIME, CE);",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugCheckerRefactoringTestHelper.newInstance;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
final class FluxFlatMapUsageCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(FluxFlatMapUsageCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
newInstance(FluxFlatMapUsageCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import java.util.function.BiFunction;",
|
||||
"import java.util.function.Function;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux.just(1).flatMap(Flux::just);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux.just(1).<String>flatMap(i -> Flux.just(String.valueOf(i)));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux.just(1).flatMapSequential(Flux::just);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux.just(1).<String>flatMapSequential(i -> Flux.just(String.valueOf(i)));",
|
||||
"",
|
||||
" Mono.just(1).flatMap(Mono::just);",
|
||||
" Flux.just(1).concatMap(Flux::just);",
|
||||
"",
|
||||
" Flux.just(1).flatMap(Flux::just, 1);",
|
||||
" Flux.just(1).flatMap(Flux::just, 1, 1);",
|
||||
" Flux.just(1).flatMap(Flux::just, throwable -> Flux.empty(), Flux::empty);",
|
||||
"",
|
||||
" Flux.just(1).flatMapSequential(Flux::just, 1);",
|
||||
" Flux.just(1).flatMapSequential(Flux::just, 1, 1);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" this.<String, Flux<String>>sink(Flux::flatMap);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMap);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" this.<String, Flux<String>>sink(Flux::flatMapSequential);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" this.<Integer, Flux<Integer>>sink(Flux::<Integer>flatMapSequential);",
|
||||
"",
|
||||
" this.<String, Mono<String>>sink(Mono::flatMap);",
|
||||
" }",
|
||||
"",
|
||||
" private <T, P> void sink(BiFunction<P, Function<T, P>, P> fun) {}",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementFirstSuggestedFix() {
|
||||
refactoringTestHelper
|
||||
.setFixChooser(FixChoosers.FIRST)
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" Flux.just(1).flatMap(Flux::just);",
|
||||
" Flux.just(1).flatMapSequential(Flux::just);",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" Flux.just(1).concatMap(Flux::just);",
|
||||
" Flux.just(1).concatMap(Flux::just);",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementSecondSuggestedFix() {
|
||||
refactoringTestHelper
|
||||
.setFixChooser(FixChoosers.SECOND)
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"",
|
||||
"class A {",
|
||||
" private static final int MAX_CONCURRENCY = 8;",
|
||||
"",
|
||||
" void m() {",
|
||||
" Flux.just(1).flatMap(Flux::just);",
|
||||
" Flux.just(1).flatMapSequential(Flux::just);",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"",
|
||||
"class A {",
|
||||
" private static final int MAX_CONCURRENCY = 8;",
|
||||
"",
|
||||
" void m() {",
|
||||
" Flux.just(1).flatMap(Flux::just, MAX_CONCURRENCY);",
|
||||
" Flux.just(1).flatMapSequential(Flux::just, MAX_CONCURRENCY);",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class FormatStringConcatenationCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(FormatStringConcatenationCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(FormatStringConcatenationCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import static com.google.common.base.Preconditions.checkArgument;",
|
||||
"import static com.google.common.base.Preconditions.checkNotNull;",
|
||||
"import static com.google.common.base.Preconditions.checkState;",
|
||||
"import static com.google.common.base.Verify.verify;",
|
||||
"import static org.assertj.core.api.Assertions.assertThat;",
|
||||
"import static org.assertj.core.api.SoftAssertions.assertSoftly;",
|
||||
"",
|
||||
"import java.util.Locale;",
|
||||
"import java.util.Formatter;",
|
||||
"import org.assertj.core.api.Assertions;",
|
||||
"import org.assertj.core.api.BDDAssertions;",
|
||||
"import org.assertj.core.api.Fail;",
|
||||
"import org.assertj.core.api.ThrowableAssertAlternative;",
|
||||
"import org.assertj.core.api.WithAssertions;",
|
||||
"import org.slf4j.Logger;",
|
||||
"import org.slf4j.LoggerFactory;",
|
||||
"import org.slf4j.Marker;",
|
||||
"",
|
||||
"class A {",
|
||||
" private static final Logger LOG = LoggerFactory.getLogger(A.class);",
|
||||
"",
|
||||
" void negative() {",
|
||||
" hashCode();",
|
||||
" equals(new A());",
|
||||
" equals(toString());",
|
||||
" equals(0);",
|
||||
" equals(\"str\");",
|
||||
" equals(\"str\" + 0);",
|
||||
" equals(0 + 0);",
|
||||
" equals(0 - 0);",
|
||||
" equals(\"str \" + toString());",
|
||||
" }",
|
||||
"",
|
||||
" void assertj() {",
|
||||
" assertThat(0).overridingErrorMessage(toString());",
|
||||
" assertThat(0).overridingErrorMessage(\"str\");",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + 0);",
|
||||
" assertThat(0).overridingErrorMessage(\"str %s\", 2 * 3);",
|
||||
" assertThat(0).overridingErrorMessage(\"str %s\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + hashCode() / 2);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).overridingErrorMessage((\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).withFailMessage(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).withFailMessage(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertSoftly(softly -> softly.fail(\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertSoftly(softly -> softly.fail(\"%s \" + toString(), \"arg\"));",
|
||||
" assertSoftly(softly -> softly.fail(\"str \" + toString(), new Throwable()));",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(\"\").isEqualTo(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(\"\").isEqualTo(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessage(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessage(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageContaining(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageContaining(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageEndingWith(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageEndingWith(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageStartingWith(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasMessageStartingWith(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasRootCauseMessage(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasRootCauseMessage(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasStackTraceContaining(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(new Error()).hasStackTraceContaining(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).as(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).as(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).describedAs(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" assertThat(0).describedAs(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessage(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessage(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageContaining(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageContaining(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageEndingWith(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageEndingWith(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageStartingWith(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withMessageStartingWith(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withStackTraceContaining(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((ThrowableAssertAlternative) null).withStackTraceContaining(\"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((WithAssertions) null).fail(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ((WithAssertions) null).fail(\"%s \" + toString(), \"arg\");",
|
||||
" ((WithAssertions) null).fail(\"str \" + toString(), new Throwable());",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Assertions.fail(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Assertions.fail(\"%s \" + toString(), \"arg\");",
|
||||
" Assertions.fail(\"str \" + toString(), new Throwable());",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" BDDAssertions.fail(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" BDDAssertions.fail(\"%s \" + toString(), \"arg\");",
|
||||
" BDDAssertions.fail(\"str \" + toString(), new Throwable());",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Fail.fail(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Fail.fail(\"%s \" + toString(), \"arg\");",
|
||||
" Fail.fail(\"str \" + toString(), new Throwable());",
|
||||
" }",
|
||||
"",
|
||||
" void guava() {",
|
||||
" checkArgument(true);",
|
||||
" checkArgument(true, toString());",
|
||||
" checkArgument(true, \"str\");",
|
||||
" checkArgument(true, \"str \" + 0);",
|
||||
" checkArgument(true, \"str %s\", 2 * 3);",
|
||||
" checkArgument(true, \"str %s\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkArgument(true, \"str \" + hashCode() / 2);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkArgument(true, (\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkArgument(true, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkArgument(true, \"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkNotNull(true, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkNotNull(true, \"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkState(true, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" checkState(true, \"%s \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" verify(true, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" verify(true, \"%s \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void jdk() {",
|
||||
" String.format(\"str\");",
|
||||
" String.format(\"str \" + 0);",
|
||||
" String.format(\"str {}\", 2 * 3);",
|
||||
" String.format(\"str {}\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(\"str \" + hashCode() / 2);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format((\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" String.format(Locale.ROOT, \"str\");",
|
||||
" String.format(Locale.ROOT, \"str \" + 0);",
|
||||
" String.format(Locale.ROOT, \"str {}\", 2 * 3);",
|
||||
" String.format(Locale.ROOT, \"str {}\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(Locale.ROOT, (\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(Locale.ROOT, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" new Formatter().format(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" new Formatter().format(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" new Formatter().format(Locale.ROOT, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" new Formatter().format(Locale.ROOT, \"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void slf4j() {",
|
||||
" LOG.debug(\"str\");",
|
||||
" LOG.debug(\"str \" + 0);",
|
||||
" LOG.debug(\"str {}\", 2 * 3);",
|
||||
" LOG.debug(\"str {}\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug(\"str \" + hashCode() / 2);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug((\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" LOG.debug((Marker) null, \"str\");",
|
||||
" LOG.debug((Marker) null, \"str \" + 0);",
|
||||
" LOG.debug((Marker) null, \"str {}\", 2 * 3);",
|
||||
" LOG.debug((Marker) null, \"str {}\", toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug((Marker) null, (\"str \" + toString()));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug((Marker) null, \"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.error(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.error(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.error((Marker) null,\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.error((Marker) null,\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.info(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.info(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.info((Marker) null,\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.info((Marker) null,\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.trace(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.trace(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.trace((Marker) null,\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.trace((Marker) null,\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.warn(\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.warn(\"{} \" + toString(), \"arg\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.warn((Marker) null,\"str \" + toString());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" LOG.warn((Marker) null,\"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import static com.google.common.base.Preconditions.checkArgument;",
|
||||
"import static org.assertj.core.api.Assertions.assertThat;",
|
||||
"",
|
||||
"import java.util.Locale;",
|
||||
"import java.util.Formatter;",
|
||||
"import org.slf4j.Logger;",
|
||||
"import org.slf4j.LoggerFactory;",
|
||||
"import org.slf4j.Marker;",
|
||||
"",
|
||||
"class A {",
|
||||
" private static final Logger LOG = LoggerFactory.getLogger(A.class);",
|
||||
"",
|
||||
" void assertj() {",
|
||||
" assertThat(0).overridingErrorMessage(toString() + \" str\");",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + toString());",
|
||||
" assertThat(0).overridingErrorMessage(toString() + toString());",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + toString() + \" word \" + new A().hashCode());",
|
||||
" assertThat(0).overridingErrorMessage(\"str \" + (toString() + \" word \") + (hashCode() / 2));",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void guava() {",
|
||||
" checkArgument(true, \"str \" + toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" checkArgument(true, \"%s \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void jdk() {",
|
||||
" String.format(\"str \" + toString());",
|
||||
" String.format(Locale.ROOT, \"str \" + toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" String.format(\"{} \" + toString(), \"arg\");",
|
||||
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void slf4j() {",
|
||||
" LOG.debug(\"str \" + toString());",
|
||||
" LOG.debug((Marker) null, \"str \" + toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" LOG.debug(\"{} \" + toString(), \"arg\");",
|
||||
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import static com.google.common.base.Preconditions.checkArgument;",
|
||||
"import static org.assertj.core.api.Assertions.assertThat;",
|
||||
"",
|
||||
"import java.util.Locale;",
|
||||
"import java.util.Formatter;",
|
||||
"import org.slf4j.Logger;",
|
||||
"import org.slf4j.LoggerFactory;",
|
||||
"import org.slf4j.Marker;",
|
||||
"",
|
||||
"class A {",
|
||||
" private static final Logger LOG = LoggerFactory.getLogger(A.class);",
|
||||
"",
|
||||
" void assertj() {",
|
||||
" assertThat(0).overridingErrorMessage(\"%s str\", toString());",
|
||||
" assertThat(0).overridingErrorMessage(\"str %s\", toString());",
|
||||
" assertThat(0).overridingErrorMessage(\"%s%s\", toString(), toString());",
|
||||
" assertThat(0).overridingErrorMessage(\"str %s word %s\", toString(), new A().hashCode());",
|
||||
" assertThat(0).overridingErrorMessage(\"str %s word %s\", toString(), hashCode() / 2);",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" assertThat(0).overridingErrorMessage(\"%s \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void guava() {",
|
||||
" checkArgument(true, \"str %s\", toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" checkArgument(true, \"%s \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"",
|
||||
" void jdk() {",
|
||||
" String.format(\"str %s\", toString());",
|
||||
" String.format(Locale.ROOT, \"str %s\", toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" String.format(\"{} \" + toString(), \"arg\");",
|
||||
" String.format(Locale.ROOT, \"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
" void slf4j() {",
|
||||
" LOG.debug(\"str {}\", toString());",
|
||||
" LOG.debug((Marker) null, \"str {}\", toString());",
|
||||
"",
|
||||
" // Flagged but not auto-fixed.",
|
||||
" LOG.debug(\"{} \" + toString(), \"arg\");",
|
||||
" LOG.debug((Marker) null, \"{} \" + toString(), \"arg\");",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
final class IdentityConversionCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(IdentityConversionCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(IdentityConversionCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"Foo.java",
|
||||
"import com.google.common.collect.ImmutableBiMap;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableListMultimap;",
|
||||
"import com.google.common.collect.ImmutableMap;",
|
||||
"import com.google.common.collect.ImmutableMultimap;",
|
||||
"import com.google.common.collect.ImmutableMultiset;",
|
||||
"import com.google.common.collect.ImmutableRangeMap;",
|
||||
"import com.google.common.collect.ImmutableRangeSet;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import com.google.common.collect.ImmutableSetMultimap;",
|
||||
"import com.google.common.collect.ImmutableTable;",
|
||||
"import reactor.adapter.rxjava.RxJava2Adapter;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"",
|
||||
"public final class Foo {",
|
||||
" public void foo() {",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Boolean b1 = Boolean.valueOf(Boolean.FALSE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Boolean b2 = Boolean.valueOf(false);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" boolean b3 = Boolean.valueOf(Boolean.FALSE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" boolean b4 = Boolean.valueOf(false);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Byte byte1 = Byte.valueOf((Byte) Byte.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Byte byte2 = Byte.valueOf(Byte.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" byte byte3 = Byte.valueOf((Byte) Byte.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" byte byte4 = Byte.valueOf(Byte.MIN_VALUE);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Character c1 = Character.valueOf((Character) 'a');",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Character c2 = Character.valueOf('a');",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" char c3 = Character.valueOf((Character) 'a');",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" char c4 = Character.valueOf('a');",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Double d1 = Double.valueOf((Double) 0.0);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Double d2 = Double.valueOf(0.0);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" double d3 = Double.valueOf((Double) 0.0);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" double d4 = Double.valueOf(0.0);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Float f1 = Float.valueOf((Float) 0.0F);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Float f2 = Float.valueOf(0.0F);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" float f3 = Float.valueOf((Float) 0.0F);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" float f4 = Float.valueOf(0.0F);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Integer i1 = Integer.valueOf((Integer) 1);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Integer i2 = Integer.valueOf(1);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" int i3 = Integer.valueOf((Integer) 1);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" int i4 = Integer.valueOf(1);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Long l1 = Long.valueOf((Long) 1L);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Long l2 = Long.valueOf(1L);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" long l3 = Long.valueOf((Long) 1L);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" long l4 = Long.valueOf(1L);",
|
||||
"",
|
||||
" Long l5 = Long.valueOf((Integer) 1);",
|
||||
" Long l6 = Long.valueOf(1);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" long l7 = Long.valueOf((Integer) 1);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" long l8 = Long.valueOf(1);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Short s1 = Short.valueOf((Short) Short.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Short s2 = Short.valueOf(Short.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" short s3 = Short.valueOf((Short) Short.MIN_VALUE);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" short s4 = Short.valueOf(Short.MIN_VALUE);",
|
||||
"",
|
||||
" String str1 = String.valueOf(0);",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" String str2 = String.valueOf(\"1\");",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableBiMap<Object, Object> o1 = ImmutableBiMap.copyOf(ImmutableBiMap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableList<Object> o2 = ImmutableList.copyOf(ImmutableList.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableListMultimap<Object, Object> o3 = ImmutableListMultimap.copyOf(ImmutableListMultimap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableMap<Object, Object> o4 = ImmutableMap.copyOf(ImmutableMap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableMultimap<Object, Object> o5 = ImmutableMultimap.copyOf(ImmutableMultimap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableMultiset<Object> o6 = ImmutableMultiset.copyOf(ImmutableMultiset.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableRangeMap<String, Object> o7 = ImmutableRangeMap.copyOf(ImmutableRangeMap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableRangeSet<String> o8 = ImmutableRangeSet.copyOf(ImmutableRangeSet.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableSet<Object> o9 = ImmutableSet.copyOf(ImmutableSet.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableSetMultimap<Object, Object> o10 = ImmutableSetMultimap.copyOf(ImmutableSetMultimap.of());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" ImmutableTable<Object, Object, Object> o11 = ImmutableTable.copyOf(ImmutableTable.of());",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux<Integer> flux1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux<Integer> flux2 = Flux.concat(Flux.just(1));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux<Integer> flux3 = Flux.firstWithSignal(Flux.just(1));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux<Integer> flux4 = Flux.from(Flux.just(1));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Flux<Integer> flux5 = Flux.merge(Flux.just(1));",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Mono<Integer> m1 = Mono.from(Mono.just(1));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Mono<Integer> m2 = Mono.fromDirect(Mono.just(1));",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementFirstSuggestedFix() {
|
||||
refactoringTestHelper
|
||||
.setFixChooser(FixChoosers.FIRST)
|
||||
.addInputLines(
|
||||
"Foo.java",
|
||||
"import static org.mockito.Mockito.when;",
|
||||
"",
|
||||
"import com.google.common.collect.ImmutableCollection;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import java.util.Collection;",
|
||||
"import java.util.ArrayList;",
|
||||
"import org.reactivestreams.Publisher;",
|
||||
"import reactor.adapter.rxjava.RxJava2Adapter;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"",
|
||||
"public final class Foo {",
|
||||
" public void foo() {",
|
||||
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());",
|
||||
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
"",
|
||||
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));",
|
||||
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
"",
|
||||
" Collection<Integer> c1 = ImmutableSet.copyOf(ImmutableSet.of(1));",
|
||||
" Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
"",
|
||||
" Flux<Integer> f1 = Flux.just(1).flatMap(e -> RxJava2Adapter.fluxToFlowable(Flux.just(2)));",
|
||||
" Flux<Integer> f2 = Flux.concat(Flux.just(3));",
|
||||
" Publisher<Integer> f3 = Flux.firstWithSignal(Flux.just(4));",
|
||||
" Publisher<Integer> f4 = Flux.from(Flux.just(5));",
|
||||
" Publisher<Integer> f5 = Flux.merge(Flux.just(6));",
|
||||
"",
|
||||
" Mono<Integer> m1 = Mono.from(Mono.just(7));",
|
||||
" Publisher<Integer> m2 = Mono.fromDirect(Mono.just(8));",
|
||||
"",
|
||||
" bar(Flux.concat(Flux.just(9)));",
|
||||
" bar(Mono.from(Mono.just(10)));",
|
||||
"",
|
||||
" Object o1 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
" Object o2 = ImmutableSet.copyOf(ImmutableSet.of());",
|
||||
"",
|
||||
" when(\"foo\".contains(\"f\"))",
|
||||
" .thenAnswer(inv-> ImmutableSet.copyOf(ImmutableList.of(1)));",
|
||||
" }",
|
||||
"",
|
||||
" void bar(Publisher<Integer> publisher) {}",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"Foo.java",
|
||||
"import static org.mockito.Mockito.when;",
|
||||
"",
|
||||
"import com.google.common.collect.ImmutableCollection;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import java.util.Collection;",
|
||||
"import java.util.ArrayList;",
|
||||
"import org.reactivestreams.Publisher;",
|
||||
"import reactor.adapter.rxjava.RxJava2Adapter;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"",
|
||||
"public final class Foo {",
|
||||
" public void foo() {",
|
||||
" ImmutableSet<Object> set1 = ImmutableSet.of();",
|
||||
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
"",
|
||||
" ImmutableCollection<Integer> list1 = ImmutableList.of(1);",
|
||||
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
"",
|
||||
" Collection<Integer> c1 = ImmutableSet.of(1);",
|
||||
" Collection<Integer> c2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
"",
|
||||
" Flux<Integer> f1 = Flux.just(1).flatMap(e -> Flux.just(2));",
|
||||
" Flux<Integer> f2 = Flux.just(3);",
|
||||
" Publisher<Integer> f3 = Flux.just(4);",
|
||||
" Publisher<Integer> f4 = Flux.just(5);",
|
||||
" Publisher<Integer> f5 = Flux.just(6);",
|
||||
"",
|
||||
" Mono<Integer> m1 = Mono.just(7);",
|
||||
" Publisher<Integer> m2 = Mono.just(8);",
|
||||
"",
|
||||
" bar(Flux.just(9));",
|
||||
" bar(Mono.just(10));",
|
||||
"",
|
||||
" Object o1 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
" Object o2 = ImmutableSet.of();",
|
||||
"",
|
||||
" when(\"foo\".contains(\"f\"))",
|
||||
" .thenAnswer(inv-> ImmutableSet.copyOf(ImmutableList.of(1)));",
|
||||
" }",
|
||||
"",
|
||||
" void bar(Publisher<Integer> publisher) {}",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementSecondSuggestedFix() {
|
||||
refactoringTestHelper
|
||||
.setFixChooser(FixChoosers.SECOND)
|
||||
.addInputLines(
|
||||
"Foo.java",
|
||||
"import com.google.common.collect.ImmutableCollection;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import java.util.ArrayList;",
|
||||
"import reactor.adapter.rxjava.RxJava2Adapter;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"",
|
||||
"public final class Foo {",
|
||||
" public void foo() {",
|
||||
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());",
|
||||
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
"",
|
||||
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));",
|
||||
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"Foo.java",
|
||||
"import com.google.common.collect.ImmutableCollection;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import java.util.ArrayList;",
|
||||
"import reactor.adapter.rxjava.RxJava2Adapter;",
|
||||
"import reactor.core.publisher.Flux;",
|
||||
"import reactor.core.publisher.Mono;",
|
||||
"",
|
||||
"public final class Foo {",
|
||||
" public void foo() {",
|
||||
" @SuppressWarnings(\"IdentityConversion\")",
|
||||
" ImmutableSet<Object> set1 = ImmutableSet.copyOf(ImmutableSet.of());",
|
||||
" ImmutableSet<Object> set2 = ImmutableSet.copyOf(ImmutableList.of());",
|
||||
"",
|
||||
" @SuppressWarnings(\"IdentityConversion\")",
|
||||
" ImmutableCollection<Integer> list1 = ImmutableList.copyOf(ImmutableList.of(1));",
|
||||
" ImmutableCollection<Integer> list2 = ImmutableList.copyOf(new ArrayList<>(ImmutableList.of(1)));",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,19 @@ import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class JUnitMethodDeclarationCheckTest {
|
||||
final class JUnitMethodDeclarationCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(JUnitMethodDeclarationCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new JUnitMethodDeclarationCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(JUnitMethodDeclarationCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import static org.junit.jupiter.params.provider.Arguments.arguments;",
|
||||
"",
|
||||
"import org.junit.jupiter.api.AfterAll;",
|
||||
"import org.junit.jupiter.api.AfterEach;",
|
||||
"import org.junit.jupiter.api.BeforeAll;",
|
||||
@@ -81,6 +83,14 @@ public final class JUnitMethodDeclarationCheckTest {
|
||||
" protected void testNonTestMethod3() {}",
|
||||
" private void testNonTestMethod4() {}",
|
||||
" @Test void test5() {}",
|
||||
"",
|
||||
" // BUG: Diagnostic contains: (but note that a method named `overload` already exists in this class)",
|
||||
" @Test void testOverload() {}",
|
||||
" void overload() {}",
|
||||
" // BUG: Diagnostic contains: (but note that `arguments` is already statically imported)",
|
||||
" @Test void testArguments() {}",
|
||||
" // BUG: Diagnostic contains: (but note that `public` is a reserved keyword)",
|
||||
" @Test void testPublic() {}",
|
||||
"}")
|
||||
.addSourceLines(
|
||||
"B.java",
|
||||
@@ -91,7 +101,7 @@ public final class JUnitMethodDeclarationCheckTest {
|
||||
"import org.junit.jupiter.api.Test;",
|
||||
"import org.junit.jupiter.params.ParameterizedTest;",
|
||||
"",
|
||||
"final class B extends A {",
|
||||
"class B extends A {",
|
||||
" @Override @BeforeAll void setUp1() {}",
|
||||
" @Override @BeforeAll public void setUp2() {}",
|
||||
" @Override @BeforeAll protected void setUp3() {}",
|
||||
@@ -122,15 +132,37 @@ public final class JUnitMethodDeclarationCheckTest {
|
||||
" @Override public void testNonTestMethod2() {}",
|
||||
" @Override protected void testNonTestMethod3() {}",
|
||||
" @Override @Test void test5() {}",
|
||||
"",
|
||||
" @Override @Test void testOverload() {}",
|
||||
" @Override void overload() {}",
|
||||
" @Override @Test void testArguments() {}",
|
||||
" @Override @Test void testPublic() {}",
|
||||
"}")
|
||||
.addSourceLines(
|
||||
"C.java",
|
||||
"import org.junit.jupiter.api.AfterAll;",
|
||||
"import org.junit.jupiter.api.BeforeAll;",
|
||||
"import org.junit.jupiter.api.Test;",
|
||||
"",
|
||||
"abstract class C {",
|
||||
" @BeforeAll public void setUp() {}",
|
||||
" @Test void testMethod1() {}",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @AfterAll private void tearDown() {}",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @Test final void testMethod2() {}",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import static org.junit.jupiter.params.provider.Arguments.arguments;",
|
||||
"",
|
||||
"import org.junit.jupiter.api.AfterAll;",
|
||||
"import org.junit.jupiter.api.AfterEach;",
|
||||
"import org.junit.jupiter.api.BeforeAll;",
|
||||
@@ -151,9 +183,16 @@ public final class JUnitMethodDeclarationCheckTest {
|
||||
" @Test public void baz() {}",
|
||||
" @RepeatedTest(2) private void qux() {}",
|
||||
" @ParameterizedTest protected void quux() {}",
|
||||
"",
|
||||
" @Test public void testOverload() {}",
|
||||
" void overload() {}",
|
||||
" @Test protected void testArguments() {}",
|
||||
" @Test private void testClass() {}",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import static org.junit.jupiter.params.provider.Arguments.arguments;",
|
||||
"",
|
||||
"import org.junit.jupiter.api.AfterAll;",
|
||||
"import org.junit.jupiter.api.AfterEach;",
|
||||
"import org.junit.jupiter.api.BeforeAll;",
|
||||
@@ -174,6 +213,11 @@ public final class JUnitMethodDeclarationCheckTest {
|
||||
" @Test void baz() {}",
|
||||
" @RepeatedTest(2) void qux() {}",
|
||||
" @ParameterizedTest void quux() {}",
|
||||
"",
|
||||
" @Test void testOverload() {}",
|
||||
" void overload() {}",
|
||||
" @Test void testArguments() {}",
|
||||
" @Test void testClass() {}",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
|
||||
@@ -19,10 +19,10 @@ public final class LexicographicalAnnotationAttributeListingCheckTest {
|
||||
"-XepOpt:LexicographicalAnnotationAttributeListing:Excludes=pkg.A.Bar#value"));
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(
|
||||
new LexicographicalAnnotationAttributeListingCheck(), getClass());
|
||||
LexicographicalAnnotationAttributeListingCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -105,7 +105,7 @@ public final class LexicographicalAnnotationAttributeListingCheckTest {
|
||||
// introduced. Avoiding that might make the code too complex. Instead, users can have the
|
||||
// `CanonicalAnnotationSyntaxCheck` correct the situation in a subsequent run.
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
@@ -161,7 +161,7 @@ public final class LexicographicalAnnotationAttributeListingCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFiltering() {
|
||||
void filtering() {
|
||||
/* Some violations are not flagged because they are not in- or excluded. */
|
||||
restrictedCompilationTestHelper
|
||||
.addSourceLines(
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.common.base.Predicates.containsPattern;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class LexicographicalAnnotationListingCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(LexicographicalAnnotationListingCheck.class, getClass())
|
||||
.expectErrorMessage(
|
||||
"X", containsPattern("Sort annotations lexicographically where possible"));
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(
|
||||
LexicographicalAnnotationListingCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import java.lang.annotation.Repeatable;",
|
||||
"",
|
||||
"interface A {",
|
||||
" @Repeatable(Foos.class)",
|
||||
" @interface Foo {",
|
||||
" String[] value() default {};",
|
||||
" int[] ints() default {};",
|
||||
" Bar[] anns() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Bar {",
|
||||
" String[] value() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Baz {",
|
||||
" String[] str() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Foos {",
|
||||
" Foo[] value();",
|
||||
" }",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Foo @Bar A unsortedSimpleCase();",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Foo() @Bar() A unsortedWithParens();",
|
||||
" @Foo() A onlyOneAnnotation();",
|
||||
" @Bar @Foo() A sortedAnnotationsOneWithParens();",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Foo @Baz @Bar A threeUnsortedAnnotationsSameInitialLetter();",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Bar @Foo() @Baz A firstOrderedWithTwoUnsortedAnnotations();",
|
||||
" @Bar @Baz @Foo() A threeSortedAnnotations();",
|
||||
"",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Foo({\"b\"}) @Bar({\"a\"}) A unsortedWithStringAttributes();",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Baz(str = {\"a\", \"b\"}) @Foo(ints = {1, 0}) @Bar A unsortedWithAttributes();",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Bar @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Baz A unsortedWithNestedBar();",
|
||||
" @Bar @Baz @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) A sortedWithNestedBar();",
|
||||
"",
|
||||
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Foo(ints = {1, 2}) @Foo({\"b\"}) A sortedRepeatableAnnotation();",
|
||||
" // BUG: Diagnostic matches: X",
|
||||
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Bar @Foo(ints = {1, 2}) A unsortedRepeatableAnnotation();",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import java.lang.annotation.Repeatable;",
|
||||
"interface A {",
|
||||
" @Repeatable(Foos.class)",
|
||||
" @interface Foo {",
|
||||
" String[] value() default {};",
|
||||
" int[] ints() default {};",
|
||||
" Bar[] anns() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Bar {",
|
||||
" String[] value() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Baz {",
|
||||
" String[] str() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Foos {",
|
||||
" Foo[] value();",
|
||||
" }",
|
||||
"",
|
||||
" @Bar A singleAnnotation();",
|
||||
" @Bar @Foo A sortedAnnotations();",
|
||||
" @Foo @Bar A unsortedAnnotations();",
|
||||
" @Foo() @Baz() @Bar A unsortedAnnotationsWithSomeParens();",
|
||||
"",
|
||||
" @Bar @Baz(str = {\"a\", \"b\"}) @Foo() A unsortedAnnotationsOneContainingAttributes();",
|
||||
" @Baz(str = {\"a\", \"b\"}) @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Bar({\"b\"}) A unsortedAnnotationsWithAttributes();",
|
||||
"",
|
||||
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Foo(ints = {1, 2}) @Foo({\"b\"}) A sortedRepeatableAnnotation();",
|
||||
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Bar @Foo(ints = {1, 2}) A unsortedRepeatableAnnotation();",
|
||||
"",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import java.lang.annotation.Repeatable;",
|
||||
"interface A {",
|
||||
" @Repeatable(Foos.class)",
|
||||
" @interface Foo {",
|
||||
" String[] value() default {};",
|
||||
" int[] ints() default {};",
|
||||
" Bar[] anns() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Bar {",
|
||||
" String[] value() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Baz {",
|
||||
" String[] str() default {};",
|
||||
" }",
|
||||
"",
|
||||
" @interface Foos {",
|
||||
" Foo[] value();",
|
||||
" }",
|
||||
" @Bar A singleAnnotation();",
|
||||
" @Bar @Foo A sortedAnnotations();",
|
||||
" @Bar @Foo A unsortedAnnotations();",
|
||||
" @Bar @Baz() @Foo() A unsortedAnnotationsWithSomeParens();",
|
||||
"",
|
||||
" @Bar @Baz(str = {\"a\", \"b\"}) @Foo() A unsortedAnnotationsOneContainingAttributes();",
|
||||
" @Bar({\"b\"}) @Baz(str = {\"a\", \"b\"}) @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) A unsortedAnnotationsWithAttributes();",
|
||||
"",
|
||||
" @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Foo(ints = {1, 2}) @Foo({\"b\"}) A sortedRepeatableAnnotation();",
|
||||
" @Bar @Foo(anns = {@Bar(\"b\"), @Bar(\"a\")}) @Foo(ints = {1, 2}) A unsortedRepeatableAnnotation();",
|
||||
"",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.errorprone.BugPattern;
|
||||
import com.google.errorprone.BugPattern.SeverityLevel;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import com.google.errorprone.VisitorState;
|
||||
import com.google.errorprone.bugpatterns.BugChecker;
|
||||
@@ -19,7 +19,7 @@ public final class MethodMatcherFactoryTest {
|
||||
/** A {@link BugChecker} which flags method invocations matched by {@link #TEST_MATCHER}. */
|
||||
@BugPattern(
|
||||
name = "MatchedMethodsFlagger",
|
||||
severity = SeverityLevel.SUGGESTION,
|
||||
severity = SUGGESTION,
|
||||
summary = "Flags methods matched by the test matcher.")
|
||||
public static final class MatchedMethodsFlagger extends BugChecker
|
||||
implements MethodInvocationTreeMatcher {
|
||||
@@ -47,7 +47,7 @@ public final class MethodMatcherFactoryTest {
|
||||
CompilationTestHelper.newInstance(MatchedMethodsFlagger.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testCreateWithMalformedSignatures() {
|
||||
void createWithMalformedSignatures() {
|
||||
MethodMatcherFactory factory = new MethodMatcherFactory();
|
||||
assertThatThrownBy(() -> factory.create(ImmutableList.of("foo.bar")))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
@@ -60,7 +60,7 @@ public final class MethodMatcherFactoryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMatcher() {
|
||||
void matcher() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"com/example/A.java",
|
||||
|
||||
@@ -9,10 +9,10 @@ public final class MethodReferenceUsageCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(MethodReferenceUsageCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new MethodReferenceUsageCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(MethodReferenceUsageCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -201,7 +201,7 @@ public final class MethodReferenceUsageCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.common.base.Predicates;
|
||||
import static com.google.common.base.Predicates.containsPattern;
|
||||
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -9,11 +10,11 @@ public final class MissingRefasterAnnotationCheckTest {
|
||||
CompilationTestHelper.newInstance(MissingRefasterAnnotationCheck.class, getClass())
|
||||
.expectErrorMessage(
|
||||
"X",
|
||||
Predicates.containsPattern(
|
||||
containsPattern(
|
||||
"The Refaster template contains a method without any Refaster annotations"));
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -72,6 +73,20 @@ public final class MissingRefasterAnnotationCheckTest {
|
||||
" map.computeIfAbsent(key, k -> function(k));",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" static final class ValidRefasterTemplate {",
|
||||
" @BeforeTemplate",
|
||||
" void unusedPureFunctionCall(Object o) {",
|
||||
" o.toString();",
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" static final class NotARefasterTemplate {",
|
||||
" @Override",
|
||||
" public String toString() {",
|
||||
" return \"This is not a Refaster template\";",
|
||||
" }",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class MockitoStubbingCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(MockitoStubbingCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(MockitoStubbingCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import static org.mockito.ArgumentMatchers.eq;",
|
||||
"import static org.mockito.ArgumentMatchers.notNull;",
|
||||
"import static org.mockito.Mockito.doAnswer;",
|
||||
"import static org.mockito.Mockito.mock;",
|
||||
"",
|
||||
"import java.util.function.BiConsumer;",
|
||||
"import java.util.function.Consumer;",
|
||||
"import org.mockito.ArgumentMatchers;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" Runnable runnable = mock(Runnable.class);",
|
||||
" doAnswer(inv -> null).when(runnable).run();",
|
||||
"",
|
||||
" Consumer<String> consumer = mock(Consumer.class);",
|
||||
" doAnswer(inv -> null).when(consumer).accept(\"foo\");",
|
||||
" doAnswer(inv -> null).when(consumer).accept(notNull());",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq(\"foo\"));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" doAnswer(inv -> null).when(consumer).accept(eq(toString()));",
|
||||
"",
|
||||
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(0, \"foo\");",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(eq(0), notNull());",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(notNull(), eq(\"foo\"));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq(\"foo\"));",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import static org.mockito.ArgumentMatchers.eq;",
|
||||
"import static org.mockito.Mockito.doAnswer;",
|
||||
"import static org.mockito.Mockito.mock;",
|
||||
"",
|
||||
"import java.util.function.BiConsumer;",
|
||||
"import java.util.function.Consumer;",
|
||||
"import org.mockito.ArgumentMatchers;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" Consumer<String> consumer = mock(Consumer.class);",
|
||||
" doAnswer(inv -> null).when(consumer).accept(ArgumentMatchers.eq(\"foo\"));",
|
||||
" doAnswer(inv -> null).when(consumer).accept(eq(toString()));",
|
||||
"",
|
||||
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(ArgumentMatchers.eq(0), ArgumentMatchers.eq(\"foo\"));",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(eq(hashCode()), eq(toString()));",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import static org.mockito.ArgumentMatchers.eq;",
|
||||
"import static org.mockito.Mockito.doAnswer;",
|
||||
"import static org.mockito.Mockito.mock;",
|
||||
"",
|
||||
"import java.util.function.BiConsumer;",
|
||||
"import java.util.function.Consumer;",
|
||||
"import org.mockito.ArgumentMatchers;",
|
||||
"",
|
||||
"class A {",
|
||||
" void m() {",
|
||||
" Consumer<String> consumer = mock(Consumer.class);",
|
||||
" doAnswer(inv -> null).when(consumer).accept(\"foo\");",
|
||||
" doAnswer(inv -> null).when(consumer).accept(toString());",
|
||||
"",
|
||||
" BiConsumer<Integer, String> biConsumer = mock(BiConsumer.class);",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(0, \"foo\");",
|
||||
" doAnswer(inv -> null).when(biConsumer).accept(hashCode(), toString());",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(PrimitiveComparisonCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new PrimitiveComparisonCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(PrimitiveComparisonCheck.class, getClass());
|
||||
|
||||
// XXX: There are no tests for multiple replacements within the same expression:
|
||||
// - Error Prone doesn't currently support this, it seems.
|
||||
@@ -19,7 +19,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
|
||||
// The logic for `char` and `short` is exactly analogous to the `byte` case.
|
||||
@Test
|
||||
public void testByteComparison() {
|
||||
void byteComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -108,7 +108,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntComparison() {
|
||||
void intComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -201,7 +201,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongComparison() {
|
||||
void longComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -278,7 +278,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFloatComparison() {
|
||||
void floatComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -335,7 +335,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoubleComparison() {
|
||||
void doubleComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -396,7 +396,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStringComparison() {
|
||||
void stringComparison() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -426,31 +426,43 @@ public final class PrimitiveComparisonCheckTest {
|
||||
.doTest();
|
||||
}
|
||||
|
||||
// XXX: If the explicit `<A, BoxedPrimitive>` generic type information was necessary, then this
|
||||
// replacement drops too much information.
|
||||
@Test
|
||||
public void testReplacementWithPrimitiveVariants() {
|
||||
void replacementWithPrimitiveVariants() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import java.util.Comparator;",
|
||||
"",
|
||||
"interface A extends Comparable<A> {",
|
||||
" Comparator<A> bCmp = Comparator.<A, Byte>comparing(o -> (byte) 0);",
|
||||
" Comparator<A> cCmp = Comparator.<A, Character>comparing(o -> (char) 0);",
|
||||
" Comparator<A> sCmp = Comparator.<A, Short>comparing(o -> (short) 0);",
|
||||
" Comparator<A> iCmp = Comparator.<A, Integer>comparing(o -> 0);",
|
||||
" Comparator<A> lCmp = Comparator.<A, Long>comparing(o -> 0L);",
|
||||
" Comparator<A> fCmp = Comparator.<A, Float>comparing(o -> 0.0f);",
|
||||
" Comparator<A> dCmp = Comparator.<A, Double>comparing(o -> 0.0);",
|
||||
" Comparator<A> bCmp = Comparator.comparing(o -> (byte) 0);",
|
||||
" Comparator<A> bCmp2 = Comparator.<A, Byte>comparing(o -> (byte) 0);",
|
||||
" Comparator<A> cCmp = Comparator.comparing(o -> (char) 0);",
|
||||
" Comparator<A> cCmp2 = Comparator.<A, Character>comparing(o -> (char) 0);",
|
||||
" Comparator<A> sCmp = Comparator.comparing(o -> (short) 0);",
|
||||
" Comparator<A> sCmp2 = Comparator.<A, Short>comparing(o -> (short) 0);",
|
||||
" Comparator<A> iCmp = Comparator.comparing(o -> 0);",
|
||||
" Comparator<A> iCmp2 = Comparator.<A, Integer>comparing(o -> 0);",
|
||||
" Comparator<A> lCmp = Comparator.comparing(o -> 0L);",
|
||||
" Comparator<A> lCmp2 = Comparator.<A, Long>comparing(o -> 0L);",
|
||||
" Comparator<A> fCmp = Comparator.comparing(o -> 0.0f);",
|
||||
" Comparator<A> fCmp2 = Comparator.<A, Float>comparing(o -> 0.0f);",
|
||||
" Comparator<A> dCmp = Comparator.comparing(o -> 0.0);",
|
||||
" Comparator<A> dCmp2 = Comparator.<A, Double>comparing(o -> 0.0);",
|
||||
"",
|
||||
" default void m() {",
|
||||
" bCmp.<Byte>thenComparing(o -> (byte) 0);",
|
||||
" bCmp.thenComparing(o -> (byte) 0);",
|
||||
" cCmp.<Character>thenComparing(o -> (char) 0);",
|
||||
" cCmp.thenComparing(o -> (char) 0);",
|
||||
" sCmp.<Short>thenComparing(o -> (short) 0);",
|
||||
" sCmp.thenComparing(o -> (short) 0);",
|
||||
" iCmp.<Integer>thenComparing(o -> 0);",
|
||||
" iCmp.thenComparing(o -> 0);",
|
||||
" lCmp.<Long>thenComparing(o -> 0L);",
|
||||
" lCmp.thenComparing(o -> 0L);",
|
||||
" fCmp.<Float>thenComparing(o -> 0.0f);",
|
||||
" fCmp.thenComparing(o -> 0.0f);",
|
||||
" dCmp.<Double>thenComparing(o -> 0.0);",
|
||||
" dCmp.thenComparing(o -> 0.0);",
|
||||
" }",
|
||||
"}")
|
||||
@@ -460,43 +472,62 @@ public final class PrimitiveComparisonCheckTest {
|
||||
"",
|
||||
"interface A extends Comparable<A> {",
|
||||
" Comparator<A> bCmp = Comparator.comparingInt(o -> (byte) 0);",
|
||||
" Comparator<A> bCmp2 = Comparator.<A>comparingInt(o -> (byte) 0);",
|
||||
" Comparator<A> cCmp = Comparator.comparingInt(o -> (char) 0);",
|
||||
" Comparator<A> cCmp2 = Comparator.<A>comparingInt(o -> (char) 0);",
|
||||
" Comparator<A> sCmp = Comparator.comparingInt(o -> (short) 0);",
|
||||
" Comparator<A> sCmp2 = Comparator.<A>comparingInt(o -> (short) 0);",
|
||||
" Comparator<A> iCmp = Comparator.comparingInt(o -> 0);",
|
||||
" Comparator<A> iCmp2 = Comparator.<A>comparingInt(o -> 0);",
|
||||
" Comparator<A> lCmp = Comparator.comparingLong(o -> 0L);",
|
||||
" Comparator<A> lCmp2 = Comparator.<A>comparingLong(o -> 0L);",
|
||||
" Comparator<A> fCmp = Comparator.comparingDouble(o -> 0.0f);",
|
||||
" Comparator<A> fCmp2 = Comparator.<A>comparingDouble(o -> 0.0f);",
|
||||
" Comparator<A> dCmp = Comparator.comparingDouble(o -> 0.0);",
|
||||
" Comparator<A> dCmp2 = Comparator.<A>comparingDouble(o -> 0.0);",
|
||||
"",
|
||||
" default void m() {",
|
||||
" bCmp.thenComparingInt(o -> (byte) 0);",
|
||||
" bCmp.thenComparingInt(o -> (byte) 0);",
|
||||
" cCmp.thenComparingInt(o -> (char) 0);",
|
||||
" cCmp.thenComparingInt(o -> (char) 0);",
|
||||
" sCmp.thenComparingInt(o -> (short) 0);",
|
||||
" sCmp.thenComparingInt(o -> (short) 0);",
|
||||
" iCmp.thenComparingInt(o -> 0);",
|
||||
" iCmp.thenComparingInt(o -> 0);",
|
||||
" lCmp.thenComparingLong(o -> 0L);",
|
||||
" lCmp.thenComparingLong(o -> 0L);",
|
||||
" fCmp.thenComparingDouble(o -> 0.0f);",
|
||||
" fCmp.thenComparingDouble(o -> 0.0f);",
|
||||
" dCmp.thenComparingDouble(o -> 0.0);",
|
||||
" dCmp.thenComparingDouble(o -> 0.0);",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
|
||||
// XXX: If the explicit `<A>` generic type information was necessary, then this replacement drops
|
||||
// too much information.
|
||||
@Test
|
||||
public void testReplacementWithBoxedVariants() {
|
||||
void replacementWithBoxedVariants() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import java.util.Comparator;",
|
||||
"",
|
||||
"interface A extends Comparable<A> {",
|
||||
" Comparator<A> bCmp = Comparator.<A>comparingInt(o -> Byte.valueOf((byte) 0));",
|
||||
" Comparator<A> cCmp = Comparator.<A>comparingInt(o -> Character.valueOf((char) 0));",
|
||||
" Comparator<A> sCmp = Comparator.<A>comparingInt(o -> Short.valueOf((short) 0));",
|
||||
" Comparator<A> iCmp = Comparator.<A>comparingInt(o -> Integer.valueOf(0));",
|
||||
" Comparator<A> lCmp = Comparator.<A>comparingLong(o -> Long.valueOf(0));",
|
||||
" Comparator<A> fCmp = Comparator.<A>comparingDouble(o -> Float.valueOf(0));",
|
||||
" Comparator<A> dCmp = Comparator.<A>comparingDouble(o -> Double.valueOf(0));",
|
||||
" Comparator<A> bCmp = Comparator.comparingInt(o -> Byte.valueOf((byte) 0));",
|
||||
" Comparator<A> bCmp2 = Comparator.<A>comparingInt(o -> Byte.valueOf((byte) 0));",
|
||||
" Comparator<A> cCmp = Comparator.comparingInt(o -> Character.valueOf((char) 0));",
|
||||
" Comparator<A> cCmp2 = Comparator.<A>comparingInt(o -> Character.valueOf((char) 0));",
|
||||
" Comparator<A> sCmp = Comparator.comparingInt(o -> Short.valueOf((short) 0));",
|
||||
" Comparator<A> sCmp2 = Comparator.<A>comparingInt(o -> Short.valueOf((short) 0));",
|
||||
" Comparator<A> iCmp = Comparator.comparingInt(o -> Integer.valueOf(0));",
|
||||
" Comparator<A> iCmp2 = Comparator.<A>comparingInt(o -> Integer.valueOf(0));",
|
||||
" Comparator<A> lCmp = Comparator.comparingLong(o -> Long.valueOf(0));",
|
||||
" Comparator<A> lCmp2 = Comparator.<A>comparingLong(o -> Long.valueOf(0));",
|
||||
" Comparator<A> fCmp = Comparator.comparingDouble(o -> Float.valueOf(0));",
|
||||
" Comparator<A> fCmp2 = Comparator.<A>comparingDouble(o -> Float.valueOf(0));",
|
||||
" Comparator<A> dCmp = Comparator.comparingDouble(o -> Double.valueOf(0));",
|
||||
" Comparator<A> dCmp2 = Comparator.<A>comparingDouble(o -> Double.valueOf(0));",
|
||||
"",
|
||||
" default void m() {",
|
||||
" bCmp.thenComparingInt(o -> Byte.valueOf((byte) 0));",
|
||||
@@ -514,12 +545,19 @@ public final class PrimitiveComparisonCheckTest {
|
||||
"",
|
||||
"interface A extends Comparable<A> {",
|
||||
" Comparator<A> bCmp = Comparator.comparing(o -> Byte.valueOf((byte) 0));",
|
||||
" Comparator<A> bCmp2 = Comparator.<A, Byte>comparing(o -> Byte.valueOf((byte) 0));",
|
||||
" Comparator<A> cCmp = Comparator.comparing(o -> Character.valueOf((char) 0));",
|
||||
" Comparator<A> cCmp2 = Comparator.<A, Character>comparing(o -> Character.valueOf((char) 0));",
|
||||
" Comparator<A> sCmp = Comparator.comparing(o -> Short.valueOf((short) 0));",
|
||||
" Comparator<A> sCmp2 = Comparator.<A, Short>comparing(o -> Short.valueOf((short) 0));",
|
||||
" Comparator<A> iCmp = Comparator.comparing(o -> Integer.valueOf(0));",
|
||||
" Comparator<A> iCmp2 = Comparator.<A, Integer>comparing(o -> Integer.valueOf(0));",
|
||||
" Comparator<A> lCmp = Comparator.comparing(o -> Long.valueOf(0));",
|
||||
" Comparator<A> lCmp2 = Comparator.<A, Long>comparing(o -> Long.valueOf(0));",
|
||||
" Comparator<A> fCmp = Comparator.comparing(o -> Float.valueOf(0));",
|
||||
" Comparator<A> fCmp2 = Comparator.<A, Float>comparing(o -> Float.valueOf(0));",
|
||||
" Comparator<A> dCmp = Comparator.comparing(o -> Double.valueOf(0));",
|
||||
" Comparator<A> dCmp2 = Comparator.<A, Double>comparing(o -> Double.valueOf(0));",
|
||||
"",
|
||||
" default void m() {",
|
||||
" bCmp.thenComparing(o -> Byte.valueOf((byte) 0));",
|
||||
@@ -535,7 +573,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacementWithPrimitiveVariantsUsingStaticImports() {
|
||||
void replacementWithPrimitiveVariantsUsingStaticImports() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
@@ -574,7 +612,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacementWithBoxedVariantsUsingStaticImports() {
|
||||
void replacementWithBoxedVariantsUsingStaticImports() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
@@ -615,7 +653,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacementWithPrimitiveVariantsInComplexSyntacticalContext() {
|
||||
void replacementWithPrimitiveVariantsInComplexSyntacticalContext() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
@@ -647,7 +685,7 @@ public final class PrimitiveComparisonCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacementWithBoxedVariantsInComplexSyntacticalContext() {
|
||||
void replacementWithBoxedVariantsInComplexSyntacticalContext() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
|
||||
@@ -18,10 +18,10 @@ public final class RedundantStringConversionCheckTest {
|
||||
ImmutableList.of(
|
||||
"-XepOpt:RedundantStringConversion:ExtraConversionMethods=java.lang.Enum#name(),A#name(),A.B#toString(int)"));
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new RedundantStringConversionCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(RedundantStringConversionCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentificationOfIdentityTransformation() {
|
||||
void identificationOfIdentityTransformation() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -44,7 +44,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationWithinMutatingAssignment() {
|
||||
void identificationWithinMutatingAssignment() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -100,7 +100,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationWithinBinaryOperation() {
|
||||
void identificationWithinBinaryOperation() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -186,7 +186,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationWithinStringBuilderMethod() {
|
||||
void identificationWithinStringBuilderMethod() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -235,7 +235,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
|
||||
// XXX: Also test the other formatter methods.
|
||||
@Test
|
||||
public void testIdentificationWithinFormatterMethod() {
|
||||
void identificationWithinFormatterMethod() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -280,7 +280,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationWithinGuavaGuardMethod() {
|
||||
void identificationWithinGuavaGuardMethod() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -340,7 +340,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationWithinSlf4jLoggerMethod() {
|
||||
void identificationWithinSlf4jLoggerMethod() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -395,7 +395,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIdentificationOfCustomConversionMethod() {
|
||||
void identificationOfCustomConversionMethod() {
|
||||
customizedCompilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -486,7 +486,7 @@ public final class RedundantStringConversionCheckTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class RefasterAnyOfUsageCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(RefasterAnyOfUsageCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(RefasterAnyOfUsageCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import com.google.errorprone.refaster.Refaster;",
|
||||
"import com.google.errorprone.refaster.annotation.BeforeTemplate;",
|
||||
"",
|
||||
"class A {",
|
||||
" @BeforeTemplate",
|
||||
" String before(String str) {",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" Refaster.anyOf();",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" return Refaster.anyOf(str);",
|
||||
" }",
|
||||
"",
|
||||
" @BeforeTemplate",
|
||||
" Object before2(String str, Object obj) {",
|
||||
" return Refaster.anyOf(str, obj);",
|
||||
" }",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import com.google.errorprone.refaster.Refaster;",
|
||||
"import com.google.errorprone.refaster.annotation.BeforeTemplate;",
|
||||
"",
|
||||
"class A {",
|
||||
" @BeforeTemplate",
|
||||
" String before(String str) {",
|
||||
" Refaster.anyOf();",
|
||||
" return Refaster.anyOf(str);",
|
||||
" }",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import com.google.errorprone.refaster.Refaster;",
|
||||
"import com.google.errorprone.refaster.annotation.BeforeTemplate;",
|
||||
"",
|
||||
"class A {",
|
||||
" @BeforeTemplate",
|
||||
" String before(String str) {",
|
||||
" Refaster.anyOf();",
|
||||
" return str;",
|
||||
" }",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,12 @@ import static java.util.function.Function.identity;
|
||||
import static java.util.function.Predicate.not;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSetMultimap;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CodeTransformer;
|
||||
import com.google.errorprone.ErrorProneFlags;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -37,10 +34,12 @@ public final class RefasterCheckTest {
|
||||
"AssertJInteger",
|
||||
"AssertJLong",
|
||||
"AssertJNumber",
|
||||
"AssertJMap",
|
||||
"AssertJObject",
|
||||
"AssertJOptional",
|
||||
"AssertJShort",
|
||||
"AssertJString",
|
||||
"AssertJThrowingCallable",
|
||||
"Assorted",
|
||||
"BigDecimal",
|
||||
"Collection",
|
||||
@@ -70,16 +69,14 @@ public final class RefasterCheckTest {
|
||||
"Stream",
|
||||
"String",
|
||||
"TestNGToAssertJ",
|
||||
"Time");
|
||||
"Time",
|
||||
"WebClient");
|
||||
/**
|
||||
* Matches the parts of the fully-qualified name of a template class that should be removed in
|
||||
* order to produce the associated {@link #TEMPLATE_GROUPS template group name}.
|
||||
*/
|
||||
private static final Pattern TEMPLATE_FQCN_TRIM_FOR_GROUP_NAME =
|
||||
Pattern.compile(".*\\.|Templates\\$.*");
|
||||
/** All Refaster templates on the classpath, indexed by their name. */
|
||||
private static final ImmutableListMultimap<String, CodeTransformer> ALL_CODE_TRANSFORMERS =
|
||||
RefasterCheck.loadAllCodeTransformers();
|
||||
/**
|
||||
* A mapping from template group names to associated template names.
|
||||
*
|
||||
@@ -87,7 +84,7 @@ public final class RefasterCheckTest {
|
||||
* templates, while the keys correspond to the associated top-level "aggregator" classes.
|
||||
*/
|
||||
private static final ImmutableSetMultimap<String, String> TEMPLATES_BY_GROUP =
|
||||
indexTemplateNamesByGroup(ALL_CODE_TRANSFORMERS.keySet());
|
||||
indexTemplateNamesByGroup(RefasterCheck.ALL_CODE_TRANSFORMERS.get().keySet());
|
||||
|
||||
/** Returns every known template group name as a parameterized test argument. */
|
||||
@SuppressWarnings("UnusedMethod" /* Used as a `@MethodSource`. */)
|
||||
@@ -104,7 +101,7 @@ public final class RefasterCheckTest {
|
||||
// XXX: Drop the filter once we have added tests for AssertJ!
|
||||
return TEMPLATES_BY_GROUP.entries().stream()
|
||||
.filter(e -> !"AssertJ".equals(e.getKey()))
|
||||
.map(e -> Arguments.of(e.getKey(), e.getValue()));
|
||||
.map(e -> arguments(e.getKey(), e.getValue()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,10 +109,10 @@ public final class RefasterCheckTest {
|
||||
* for all of the {@link #TEMPLATE_GROUPS}.
|
||||
*
|
||||
* <p>This test is just as much about ensuring that {@link #TEMPLATE_GROUPS} is exhaustive, so
|
||||
* that in turn {@link #testReplacement}'s coverage is exhaustive.
|
||||
* that in turn {@link #replacement}'s coverage is exhaustive.
|
||||
*/
|
||||
@Test
|
||||
public void testLoadAllCodeTransformers() {
|
||||
void loadAllCodeTransformers() {
|
||||
assertThat(TEMPLATES_BY_GROUP.keySet()).hasSameElementsAs(TEMPLATE_GROUPS);
|
||||
}
|
||||
|
||||
@@ -123,9 +120,9 @@ public final class RefasterCheckTest {
|
||||
* Verifies for each of the {@link #TEMPLATE_GROUPS} that the associated code transformers have
|
||||
* the desired effect.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@MethodSource("templateGroupsUnderTest")
|
||||
public void testReplacement(String group) {
|
||||
@ParameterizedTest
|
||||
void replacement(String group) {
|
||||
verifyRefactoring(group, namePattern(group));
|
||||
}
|
||||
|
||||
@@ -136,9 +133,9 @@ public final class RefasterCheckTest {
|
||||
* com.google.errorprone.refaster.Refaster#anyOf} branches are tested. Idem for {@link
|
||||
* com.google.errorprone.refaster.annotation.BeforeTemplate} methods in case there are multiple .
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@MethodSource("templatesUnderTest")
|
||||
public void testCoverage(String group, String template) {
|
||||
@ParameterizedTest
|
||||
void coverage(String group, String template) {
|
||||
assertThatCode(() -> verifyRefactoring(group, namePattern(group, template)))
|
||||
.withFailMessage(
|
||||
"Template %s does not affect the tests for group %s; is it tested?", template, group)
|
||||
@@ -172,9 +169,23 @@ public final class RefasterCheckTest {
|
||||
private BugCheckerRefactoringTestHelper createRestrictedRefactoringTestHelper(
|
||||
String namePattern) {
|
||||
return BugCheckerRefactoringTestHelper.newInstance(
|
||||
new RefasterCheck(
|
||||
ErrorProneFlags.fromMap(ImmutableMap.of("Refaster:NamePattern", namePattern)),
|
||||
ALL_CODE_TRANSFORMERS),
|
||||
getClass());
|
||||
RefasterCheck.class, getRefasterTemplateCollectionClass())
|
||||
.setArgs("-XepOpt:Refaster:NamePattern=" + namePattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an arbitrary Refaster template collection class inside the {@code
|
||||
* tech.picnic.errorprone.refastertemplates} package, enabling {@link
|
||||
* BugCheckerRefactoringTestHelper} to load test resources from said package.
|
||||
*/
|
||||
private Class<?> getRefasterTemplateCollectionClass() {
|
||||
try {
|
||||
return Class.forName(
|
||||
"tech.picnic.errorprone.refastertemplates.AssortedTemplates",
|
||||
/* initialize= */ false,
|
||||
getClass().getClassLoader());
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new IllegalStateException("Failed to load Refaster template collection class", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,16 +3,19 @@ package tech.picnic.errorprone.bugpatterns;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public final class RequestMappingAnnotationCheckTest {
|
||||
final class RequestMappingAnnotationCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(RequestMappingAnnotationCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import java.io.InputStream;",
|
||||
"import java.time.ZoneId;",
|
||||
"import java.util.Locale;",
|
||||
"import java.util.TimeZone;",
|
||||
"import javax.servlet.http.HttpServletRequest;",
|
||||
"import javax.servlet.http.HttpServletResponse;",
|
||||
"import org.springframework.http.HttpMethod;",
|
||||
@@ -27,7 +30,11 @@ public final class RequestMappingAnnotationCheckTest {
|
||||
"import org.springframework.web.bind.annotation.RequestMapping;",
|
||||
"import org.springframework.web.bind.annotation.RequestMethod;",
|
||||
"import org.springframework.web.bind.annotation.RequestParam;",
|
||||
"import org.springframework.web.context.request.NativeWebRequest;",
|
||||
"import org.springframework.web.context.request.WebRequest;",
|
||||
"import org.springframework.web.server.ServerWebExchange;",
|
||||
"import org.springframework.web.util.UriBuilder;",
|
||||
"import org.springframework.web.util.UriComponentsBuilder;",
|
||||
"",
|
||||
"interface A {",
|
||||
" A noMapping();",
|
||||
@@ -38,10 +45,17 @@ public final class RequestMappingAnnotationCheckTest {
|
||||
" @PostMapping A properRequestHeader(@RequestHeader String header);",
|
||||
" @PutMapping A properRequestParam(@RequestParam String param);",
|
||||
" @RequestMapping A properInputStream(InputStream input);",
|
||||
" @RequestMapping A properZoneId(ZoneId zoneId);",
|
||||
" @RequestMapping A properLocale(Locale locale);",
|
||||
" @RequestMapping A properTimeZone(TimeZone timeZone);",
|
||||
" @RequestMapping A properHttpServletRequest(HttpServletRequest request);",
|
||||
" @RequestMapping A properHttpServletResponse(HttpServletResponse response);",
|
||||
" @RequestMapping A properHttpMethod(HttpMethod method);",
|
||||
" @RequestMapping A properNativeWebRequest(NativeWebRequest request);",
|
||||
" @RequestMapping A properWebRequest(WebRequest request);",
|
||||
" @RequestMapping A properServerWebExchange(ServerWebExchange exchange);",
|
||||
" @RequestMapping A properServerUriBuilder(UriBuilder builder);",
|
||||
" @RequestMapping A properServerUriComponentsBuilder(UriComponentsBuilder builder);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @DeleteMapping A delete(String param);",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
final class RequestParamTypeCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(RequestParamTypeCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import com.google.common.collect.ImmutableBiMap;",
|
||||
"import com.google.common.collect.ImmutableList;",
|
||||
"import com.google.common.collect.ImmutableMap;",
|
||||
"import com.google.common.collect.ImmutableSet;",
|
||||
"import java.util.List;",
|
||||
"import java.util.Map;",
|
||||
"import java.util.Set;",
|
||||
"import javax.annotation.Nullable;",
|
||||
"import org.springframework.web.bind.annotation.DeleteMapping;",
|
||||
"import org.springframework.web.bind.annotation.GetMapping;",
|
||||
"import org.springframework.web.bind.annotation.PostMapping;",
|
||||
"import org.springframework.web.bind.annotation.PutMapping;",
|
||||
"import org.springframework.web.bind.annotation.RequestBody;",
|
||||
"import org.springframework.web.bind.annotation.RequestParam;",
|
||||
"",
|
||||
"interface A {",
|
||||
" @PostMapping A properRequestParam(@RequestBody String body);",
|
||||
" @GetMapping A properRequestParam(@RequestParam int param);",
|
||||
" @GetMapping A properRequestParam(@RequestParam List<String> param);",
|
||||
" @PostMapping A properRequestParam(@RequestBody String body, @RequestParam Set<String> param);",
|
||||
" @PutMapping A properRequestParam(@RequestBody String body, @RequestParam Map<String, String> param);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @GetMapping A get(@RequestParam ImmutableBiMap<String, String> param);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @PostMapping A post(@Nullable @RequestParam ImmutableList<String> param);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @PutMapping A put(@RequestBody String body, @RequestParam ImmutableSet<String> param);",
|
||||
"",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @DeleteMapping A delete(@RequestBody String body, @RequestParam ImmutableMap<String, String> param);",
|
||||
"",
|
||||
" void negative(ImmutableSet<Integer> set, ImmutableMap<String, String> map);",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package tech.picnic.errorprone.bugpatterns;
|
||||
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper;
|
||||
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
|
||||
import com.google.errorprone.CompilationTestHelper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.DisabledForJreRange;
|
||||
import org.junit.jupiter.api.condition.JRE;
|
||||
|
||||
public final class ScheduledTransactionTraceCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(ScheduledTransactionTraceCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(ScheduledTransactionTraceCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
"import com.newrelic.api.agent.Trace;",
|
||||
"import org.springframework.scheduling.annotation.Scheduled;",
|
||||
"",
|
||||
"class A {",
|
||||
" void notScheduled() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" void scheduledButNotTraced() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @Trace",
|
||||
" void scheduledButImproperlyTraced1() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" // BUG: Diagnostic contains:",
|
||||
" @Trace(dispatcher = false)",
|
||||
" void scheduledButImproperlyTraced2() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(dispatcher = true)",
|
||||
" void scheduledAndProperlyTraced() {}",
|
||||
"}")
|
||||
.doTest();
|
||||
}
|
||||
|
||||
// XXX: Enable this test for all JREs once https://github.com/google/error-prone/pull/2820 is
|
||||
// merged and released.
|
||||
@Test
|
||||
@DisabledForJreRange(min = JRE.JAVA_12)
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
"import com.newrelic.api.agent.Trace;",
|
||||
"import org.springframework.scheduling.annotation.Scheduled;",
|
||||
"",
|
||||
"class A {",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" void scheduledButNotTraced() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace",
|
||||
" void scheduledButImproperlyTraced1() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(dispatcher = false)",
|
||||
" void scheduledButImproperlyTraced2() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(leaf = true)",
|
||||
" void scheduledButImproperlyTraced3() {}",
|
||||
"}")
|
||||
.addOutputLines(
|
||||
"out/A.java",
|
||||
"import com.newrelic.api.agent.Trace;",
|
||||
"import org.springframework.scheduling.annotation.Scheduled;",
|
||||
"",
|
||||
"class A {",
|
||||
" @Trace(dispatcher = true)",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" void scheduledButNotTraced() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(dispatcher = true)",
|
||||
" void scheduledButImproperlyTraced1() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(dispatcher = true)",
|
||||
" void scheduledButImproperlyTraced2() {}",
|
||||
"",
|
||||
" @Scheduled(fixedDelay = 1)",
|
||||
" @Trace(dispatcher = true, leaf = true)",
|
||||
" void scheduledButImproperlyTraced3() {}",
|
||||
"}")
|
||||
.doTest(TestMode.TEXT_MATCH);
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,10 @@ public final class Slf4jLogStatementCheckTest {
|
||||
private final CompilationTestHelper compilationTestHelper =
|
||||
CompilationTestHelper.newInstance(Slf4jLogStatementCheck.class, getClass());
|
||||
private final BugCheckerRefactoringTestHelper refactoringTestHelper =
|
||||
BugCheckerRefactoringTestHelper.newInstance(new Slf4jLogStatementCheck(), getClass());
|
||||
BugCheckerRefactoringTestHelper.newInstance(Slf4jLogStatementCheck.class, getClass());
|
||||
|
||||
@Test
|
||||
public void testIdentification() {
|
||||
void identification() {
|
||||
compilationTestHelper
|
||||
.addSourceLines(
|
||||
"A.java",
|
||||
@@ -92,7 +92,7 @@ public final class Slf4jLogStatementCheckTest {
|
||||
|
||||
// XXX: Drop what's unused.
|
||||
@Test
|
||||
public void testReplacement() {
|
||||
void replacement() {
|
||||
refactoringTestHelper
|
||||
.addInputLines(
|
||||
"in/A.java",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user