Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ private static class RemoveTestPrefixVisitor extends JavaIsoVisitor<ExecutionCon

private static final AnnotationMatcher ANNOTATION_MATCHER = new AnnotationMatcher("@org.junit.jupiter.params.provider.MethodSource");
private static final String STATIC_IMPORTS = "STATIC_IMPORTS";
private static final List<AnnotationMatcher> JUNIT5_TEST_ANNOTATIONS = Arrays.asList(
new AnnotationMatcher("@org.junit.jupiter.api.Test"),
new AnnotationMatcher("@org.junit.jupiter.api.RepeatedTest"),
new AnnotationMatcher("@org.junit.jupiter.params.ParameterizedTest"),
new AnnotationMatcher("@org.junit.jupiter.api.TestFactory"),
new AnnotationMatcher("@org.junit.jupiter.api.TestTemplate"));

@Override
public J.Import visitImport(J.Import _import, ExecutionContext ctx) {
Expand Down Expand Up @@ -187,12 +193,10 @@ private boolean methodExists(JavaType.Method method, String newName) {

private static boolean hasJUnit5MethodAnnotation(MethodDeclaration method) {
for (J.Annotation a : method.getLeadingAnnotations()) {
if (TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.Test") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.RepeatedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.params.ParameterizedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.TestFactory") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.TestTemplate")) {
return true;
for (AnnotationMatcher matcher : JUNIT5_TEST_ANNOTATIONS) {
if (matcher.matches(a)) {
return true;
}
}
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.jetbrains.annotations.Contract;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.*;
Expand All @@ -27,12 +28,19 @@
import java.time.Duration;
import java.util.List;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;

public class SimplifyTestThrows extends Recipe {

private static final String FQN_JAVA_LANG_EXCEPTION = "java.lang.Exception";
private static final List<AnnotationMatcher> JUNIT5_TEST_ANNOTATIONS = asList(
new AnnotationMatcher("@org.junit.jupiter.api.Test"),
new AnnotationMatcher("@org.junit.jupiter.api.TestTemplate"),
new AnnotationMatcher("@org.junit.jupiter.api.RepeatedTest"),
new AnnotationMatcher("@org.junit.jupiter.params.ParameterizedTest"),
new AnnotationMatcher("@org.junit.jupiter.api.TestFactory"));

@Getter
final String displayName = "Simplify `throws` statements of tests";
Expand Down Expand Up @@ -96,19 +104,17 @@ private boolean throwsNothingOrExceptionOrThrowable(@Nullable List<NameTree> th)
(TypeUtils.isOfClassType(th.get(0).getType(), FQN_JAVA_LANG_EXCEPTION) ||
TypeUtils.isOfClassType(th.get(0).getType(), "java.lang.Throwable"));
}

private boolean hasJUnit5MethodAnnotation(J.MethodDeclaration method) {
for (J.Annotation a : method.getLeadingAnnotations()) {
if (TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.Test") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.TestTemplate") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.RepeatedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.params.ParameterizedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.TestFactory")) {
return true;
}
}
return false;
}
});
}

private static boolean hasJUnit5MethodAnnotation(J.MethodDeclaration method) {
for (J.Annotation a : method.getLeadingAnnotations()) {
for (AnnotationMatcher matcher : JUNIT5_TEST_ANNOTATIONS) {
if (matcher.matches(a)) {
return true;
}
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.UsesType;
Expand All @@ -33,13 +34,20 @@
import org.openrewrite.java.tree.TypeUtils;
import org.openrewrite.staticanalysis.java.JavaFileChecker;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;

public class TestMethodsShouldBeVoid extends Recipe {

private static final String TEST_ANNOTATION_TYPE_PATTERN = "org..*Test";
private static final List<AnnotationMatcher> JUNIT5_TEST_ANNOTATIONS = asList(
new AnnotationMatcher("@org.junit.jupiter.api.Test"),
new AnnotationMatcher("@org.junit.jupiter.api.RepeatedTest"),
new AnnotationMatcher("@org.junit.jupiter.params.ParameterizedTest"),
new AnnotationMatcher("@org.junit.jupiter.api.TestTemplate"));

@Getter
final String displayName = "Test methods should have void return type";
Expand Down Expand Up @@ -157,11 +165,10 @@ public J.MemberReference visitMemberReference(J.MemberReference memberRef, Atomi

private static boolean hasJUnit5MethodAnnotation(J.MethodDeclaration method) {
for (J.Annotation a : method.getLeadingAnnotations()) {
if (TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.Test") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.RepeatedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.params.ParameterizedTest") ||
TypeUtils.isOfClassType(a.getType(), "org.junit.jupiter.api.TestTemplate")) {
return true;
for (AnnotationMatcher matcher : JUNIT5_TEST_ANNOTATIONS) {
if (matcher.matches(a)) {
return true;
}
}
}
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.SemanticallyEqual;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
Expand Down Expand Up @@ -118,7 +119,7 @@ private boolean isExpectInvocation(J.MethodInvocation mi, J.Identifier dependenc
mi.getArguments().size() == 1 &&
mi.getArguments().get(0) instanceof J.MethodInvocation &&
((J.MethodInvocation) mi.getArguments().get(0)).getSelect() instanceof J.Identifier &&
dependency.getSimpleName().equals(((J.Identifier) ((J.MethodInvocation) mi.getArguments().get(0)).getSelect()).getSimpleName());
SemanticallyEqual.areEqual(dependency, ((J.MethodInvocation) mi.getArguments().get(0)).getSelect());
}

// match: expect(<dep>.someMethod()).andReturn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package org.openrewrite.java.testing.hamcrest;

import lombok.Getter;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
Expand Down Expand Up @@ -83,6 +84,7 @@ enum Replacement {

final String hamcrest, junitPositive, junitNegative, template, kotlinTemplate;
final String argumentsMethod;
final MethodMatcher matcher;

Replacement(String hamcrest, String junitPositive, String junitNegative, String template, String argumentsMethod) {
this(hamcrest, junitPositive, junitNegative, template, template, argumentsMethod);
Expand All @@ -95,6 +97,16 @@ enum Replacement {
this.template = template;
this.kotlinTemplate = kotlinTemplate;
this.argumentsMethod = argumentsMethod;
this.matcher = new MethodMatcher("org.hamcrest..* " + hamcrest + "(..)");
}

static @Nullable Replacement of(J.MethodInvocation matcherInvocation) {
for (Replacement replacement : values()) {
if (replacement.matcher.matches(matcherInvocation)) {
return replacement;
}
}
return null;
}

private static final Map<String, BiFunction<Expression, J.MethodInvocation, List<Expression>>> methods = new HashMap<>();
Expand Down Expand Up @@ -167,10 +179,8 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
}
}

Replacement replacement;
try {
replacement = Replacement.valueOf(matcherInvocation.getSimpleName().toUpperCase());
} catch (IllegalArgumentException e) {
Replacement replacement = Replacement.of(matcherInvocation);
if (replacement == null) {
return mi;
}
boolean kotlin = getCursor().firstEnclosing(K.CompilationUnit.class) != null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,8 @@ private static boolean isJmockitArgumentMatcher(Expression expression) {
return false;
}
J.Identifier identifier = (J.Identifier) expression;
return JMOCKIT_ARGUMENT_MATCHERS.contains(identifier.getSimpleName());
return JMOCKIT_ARGUMENT_MATCHERS.contains(identifier.getSimpleName()) &&
identifier.getFieldType() != null &&
TypeUtils.isOfClassType(identifier.getFieldType().getOwner(), "mockit.Invocations");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import org.openrewrite.Tree;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.SemanticallyEqual;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;

Expand All @@ -38,6 +40,7 @@

class JMockitBlockRewriter {

private static final MethodMatcher RETURNS_MATCHER = new MethodMatcher("mockit.Expectations returns(..)");
private static final String WHEN_TEMPLATE_PREFIX = "when(#{any()}).";
private static final String VERIFY_NO_INTERACTIONS_TEMPLATE_PREFIX = "verifyNoMoreInteractions(";
private static final String VERIFY_IN_ORDER_TEMPLATE_PREFIX_1 = "InOrder inOrder";
Expand Down Expand Up @@ -124,12 +127,12 @@ J.Block rewriteMethodBody() {
if (select instanceof J.Identifier) {
J.Identifier mockObj = (J.Identifier) select;
// ensure it's not a returns statement, we add that later to related statements
if (!"returns".equals(invocation.getName().getSimpleName())) {
if (!RETURNS_MATCHER.matches(invocation)) {
methodInvocationIdx++;
methodInvocationsToRewrite.add(new ArrayList<>());
}
if ((isFullVerifications() || isVerificationsInOrder()) &&
uniqueMocks.stream().noneMatch(mock -> mock.getSimpleName().equals(mockObj.getSimpleName()))) {
uniqueMocks.stream().noneMatch(mock -> SemanticallyEqual.areEqual(mock, mockObj))) {
uniqueMocks.add(mockObj);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import lombok.AllArgsConstructor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.SemanticallyEqual;
import org.openrewrite.java.tree.*;

import java.util.ArrayList;
Expand All @@ -42,10 +43,10 @@ J.Block rewriteMethodBody() {
continue;
}
J.NewClass nc = (J.NewClass) s;
Set<String> spies = new HashSet<>();
List<J.Identifier> spies = new ArrayList<>();
for (Expression newClassArg : nc.getArguments()) {
if (newClassArg instanceof J.Identifier) {
spies.add(((J.Identifier) newClassArg).getSimpleName());
spies.add((J.Identifier) newClassArg);
}
}

Expand Down Expand Up @@ -139,7 +140,7 @@ private void rewriteBodyStatement(Statement statement, JavaCoordinates coordinat
methodBody = methodBody.withStatements(statements);
}

private boolean isSetupStatement(Statement expectationStatement, Set<String> spies) {
private boolean isSetupStatement(Statement expectationStatement, List<J.Identifier> spies) {
if (expectationStatement instanceof J.MethodInvocation) {
// a method invocation on a mock is not a setup statement
J.MethodInvocation methodInvocation = (J.MethodInvocation) expectationStatement;
Expand Down Expand Up @@ -179,8 +180,8 @@ private static JavaType getVariableTypeFromAssignment(J.Assignment assignment) {
return identifier.getFieldType() != null ? identifier.getFieldType().getOwner() : identifier.getType();
}

private static boolean isNotMockIdentifier(J.Identifier identifier, Set<String> spies) {
if (spies.contains(identifier.getSimpleName())) {
private static boolean isNotMockIdentifier(J.Identifier identifier, List<J.Identifier> spies) {
if (spies.stream().anyMatch(spy -> SemanticallyEqual.areEqual(spy, identifier))) {
return false;
}
if (identifier.getType() instanceof JavaType.Method &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.ChangeMethodTargetToStatic;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.*;

Expand All @@ -47,6 +48,10 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {

public static class AssertToAssertionsVisitor extends JavaIsoVisitor<ExecutionContext> {
private static final JavaType ASSERTION_TYPE = JavaType.buildType("org.junit.Assert");
private static final MethodMatcher ASSERT_MATCHER = new MethodMatcher("org.junit.Assert *(..)");
private static final MethodMatcher ASSERT_THAT_MATCHER = new MethodMatcher("org.junit.Assert assertThat(..)");
private static final MethodMatcher ASSERT_SAME_OR_NOT_SAME_MATCHER = new MethodMatcher("org.junit.Assert assert*Same(*, *)");
private static final MethodMatcher ASSERT_EQUALS_OR_NOT_EQUALS_MATCHER = new MethodMatcher("org.junit.Assert assert*Equals(*, *)");

@Override
public @Nullable J preVisit(J tree, ExecutionContext ctx) {
Expand Down Expand Up @@ -90,13 +95,8 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
List<JRightPadded<Expression>> args = m.getPadding().getArguments().getPadding().getElements();
Expression firstArg = args.get(0).getElement();
// Suppress arg-switching for Assertions.assertEquals(String, String)
if (args.size() == 2) {
if ("assertSame".equals(m.getSimpleName()) ||
"assertNotSame".equals(m.getSimpleName()) ||
"assertEquals".equals(m.getSimpleName()) ||
"assertNotEquals".equals(m.getSimpleName())) {
return m;
}
if (ASSERT_SAME_OR_NOT_SAME_MATCHER.matches(m) || ASSERT_EQUALS_OR_NOT_EQUALS_MATCHER.matches(m)) {
return m;
}
if (TypeUtils.isString(firstArg.getType())) {
// Move the first arg to be the last argument
Expand Down Expand Up @@ -149,15 +149,8 @@ public J.MemberReference visitMemberReference(J.MemberReference memberRef, Execu
return mr;
}

private static boolean isJunitAssertMethod(MethodCall memberRef) {
if (memberRef.getMethodType() == null || !TypeUtils.isOfType(ASSERTION_TYPE, memberRef.getMethodType().getDeclaringType())) {
return false;
}
if (memberRef instanceof J.MemberReference) {
return !"assertThat".equals(((J.MemberReference) memberRef).getReference().getSimpleName());
}
return memberRef instanceof J.MethodInvocation &&
!"assertThat".equals(((J.MethodInvocation) memberRef).getSimpleName());
private static boolean isJunitAssertMethod(MethodCall call) {
return ASSERT_MATCHER.matches(call) && !ASSERT_THAT_MATCHER.matches(call);
}
}
}
Loading
Loading