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 @@ -26,6 +26,9 @@
import org.openrewrite.java.tree.J;

import java.util.Comparator;
import java.util.List;

import static java.util.Collections.singletonList;

public class ReplaceArquillianInSequenceAnnotation extends Recipe {
private static final String IN_SEQUENCE = "org.jboss.arquillian.junit.InSequence";
Expand All @@ -40,17 +43,16 @@ public class ReplaceArquillianInSequenceAnnotation extends Recipe {
@Getter
final String description = "Transforms the Arquillian JUnit 4 `@InSequence` to the JUnit Jupiter `@Order`.";

@Override
public List<Recipe> getRecipeList() {
return singletonList(new ChangeType(IN_SEQUENCE, "org.junit.jupiter.api.Order", true));
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
new UsesType<>("org.jboss.arquillian.junit.InSequence", false),
new UsesType<>(IN_SEQUENCE, false),
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
doAfterVisit(new ChangeType(IN_SEQUENCE, "org.junit.jupiter.api.Order", true).getVisitor());
return super.visitClassDeclaration(classDecl, ctx);
}

@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
.apply(getCursor(), mi.getCoordinates().replace(), args.toArray());
}

doAfterVisit(new RemoveUnusedImports().getVisitor());
maybeRemoveImport(JUNIT);
doAfterVisit(new UnqualifiedMethodInvocations());
return mi;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,9 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
maybeRemoveImport(JMOCKIT_MOCKUP_IMPORT);
maybeAddImport(MOCKITO_ALL_IMPORT.replace(".*", ""), "*", false);

doAfterVisit(new LambdaBlockToExpression().getVisitor());
if (md != methodDecl) {
md = (J.MethodDeclaration) new LambdaBlockToExpression().getVisitor().visitNonNull(md, ctx, getCursor().getParentOrThrow());
}
doAfterVisit(ShortenFullyQualifiedTypeReferences.modifyOnly(md));
return maybeAutoFormat(methodDecl, md, ctx);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
if (m.getBody() == null) {
return m;
}
doAfterVisit(new LambdaBlockToExpression().getVisitor());
return m.withBody(m.getBody().withStatements(ListUtils.flatMap(m.getBody().getStatements(), methodStatement -> {
J statementToCheck = methodStatement;
final J.VariableDeclarations assertThrowsWithVarDec;
Expand Down Expand Up @@ -136,6 +135,9 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl
return argument;
})
);
if (getCursor().firstEnclosing(J.CompilationUnit.class) != null) {
newAssertThrows = (J.MethodInvocation) new LambdaBlockToExpression().getVisitor().visitNonNull(newAssertThrows, ctx, getCursor());
}

if (assertThrowsWithVarDec == null) {
variableAssignments.add(newAssertThrows);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@
import org.openrewrite.java.tree.*;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toList;

public class AssertToAssertions extends Recipe {
Expand All @@ -48,6 +51,7 @@ 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 String ASSERT_METHOD_NAMES = "assertMethodNames";
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(*, *)");
Expand Down Expand Up @@ -88,9 +92,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
if (!isJunitAssertMethod(m)) {
return m;
}
doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + m.getSimpleName() + "(..)",
"org.junit.jupiter.api.Assertions", null, null, true)
.getVisitor());
changeTargetToAssertions(m.getSimpleName());

List<JRightPadded<Expression>> args = m.getPadding().getArguments().getPadding().getElements();
Expression firstArg = args.get(0).getElement();
Expand Down Expand Up @@ -142,13 +144,25 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
public J.MemberReference visitMemberReference(J.MemberReference memberRef, ExecutionContext ctx) {
J.MemberReference mr = super.visitMemberReference(memberRef, ctx);
if (isJunitAssertMethod(mr)) {
doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + mr.getReference().getSimpleName() + "(..)",
"org.junit.jupiter.api.Assertions", null, null, true)
.getVisitor());
changeTargetToAssertions(mr.getReference().getSimpleName());
}
return mr;
}

@Override
public J postVisit(J tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
for (String methodName : getCursor().<Set<String>>getMessage(ASSERT_METHOD_NAMES, emptySet())) {
doAfterVisit(new ChangeMethodTargetToStatic("org.junit.Assert " + methodName + "(..)", "org.junit.jupiter.api.Assertions", null, null, true).getVisitor());
}
}
return tree;
}

private void changeTargetToAssertions(String methodName) {
getCursor().dropParentUntil(JavaSourceFile.class::isInstance).computeMessageIfAbsent(ASSERT_METHOD_NAMES, k -> new LinkedHashSet<String>()).add(methodName);
}

private static boolean isJunitAssertMethod(MethodCall call) {
return ASSERT_MATCHER.matches(call) && !ASSERT_THAT_MATCHER.matches(call);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,6 @@ private static class ExpectedExceptionToAssertThrowsVisitor extends JavaIsoVisit
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
// Only a migrated method can have produced the lambda that needs collapsing.
if (cd != classDecl) {
doAfterVisit(new LambdaBlockToExpression().getVisitor());
}

// A method that could not be migrated still needs the rule, so leave the field and its imports in place.
boolean cannotMigrate = getCursor().getMessage(CANNOT_MIGRATE) != null;
Expand Down Expand Up @@ -197,6 +193,7 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {

maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows", false);
Statement firstExpectedExceptionMethodInvocation = getCursor().getMessage(FIRST_EXPECTED_EXCEPTION_METHOD_INVOCATION);
int assertThrowsIndex = b.getStatements().indexOf(firstExpectedExceptionMethodInvocation);
String templateString = exceptionClass instanceof String ? "#{}assertThrows(#{}, () -> #{any()});" : "#{}assertThrows(#{any()}, () -> #{any()});";
b = JavaTemplate.builder(templateString)
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3"))
Expand Down Expand Up @@ -239,6 +236,7 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
}
return removeStatement.get() ? null : statement;
}));
b = b.withStatements(ListUtils.map(b.getStatements(), (i, statement) -> i == assertThrowsIndex ? (Statement) new LambdaBlockToExpression().getVisitor().visitNonNull(statement, ctx, updateCursor) : statement));
Statement lastStatement = b.getStatements().get(b.getStatements().size() - 1);
if (!findSuccessorStatements(new Cursor(updateCursor(b), lastStatement)).isEmpty()) {
J.Return returnStatement = new J.Return(randomId(), b.getStatements().get(b.getStatements().size() - 1).getPrefix().withComments(emptyList()), Markers.EMPTY, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,7 @@ public ParametersNoArgsImplicitMethodSource(Set<String> initMethods, Map<String,
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
// Remove @RunWith(JUnitParamsRunner.class) annotation
doAfterVisit(new RemoveAnnotationVisitor(RUN_WITH_JUNIT_PARAMS_ANNOTATION_MATCHER));
cd = (J.ClassDeclaration) new RemoveAnnotationVisitor(RUN_WITH_JUNIT_PARAMS_ANNOTATION_MATCHER).visitNonNull(cd, ctx, getCursor().getParentOrThrow());
List<String> methodNames = getCursor().getMessage(MakeMethodStatic.REFERENCED_METHODS, emptyList());
if (cd.getType() != null && !methodNames.isEmpty()) {
doAfterVisit(new MakeMethodStatic(cd.getType(), methodNames));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.RemoveAnnotation;
import org.openrewrite.java.RemoveAnnotationVisitor;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;

Expand Down Expand Up @@ -49,12 +50,13 @@ public class RemoveObsoleteRunnersVisitor extends JavaIsoVisitor<ExecutionContex

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = classDecl;
for (String runner : obsoleteRunners) {
doAfterVisit(new RemoveAnnotation("@org.junit.runner.RunWith(" + runner + ".class)").getVisitor());
cd = (J.ClassDeclaration) new RemoveAnnotationVisitor(new AnnotationMatcher("@org.junit.runner.RunWith(" + runner + ".class)")).visitNonNull(cd, ctx, getCursor().getParentOrThrow());
maybeRemoveImport(runner);
}
maybeRemoveImport("org.junit.runner.RunWith");
return classDecl;
return cd;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@
import org.openrewrite.java.tree.J;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

public class UpdateBeforeAfterAnnotations extends Recipe {
@Getter
final String displayName = "Migrate JUnit 4 lifecycle annotations to JUnit Jupiter";
Expand All @@ -56,20 +59,12 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
new UsesType<>("org.junit.After", false),
new UsesType<>("org.junit.AfterClass", false)
),
new UpdateBeforeAfterAnnotationsVisitor());
new RemoveRedundantJUnit4LifecycleAnnotations());
}

public static class UpdateBeforeAfterAnnotationsVisitor extends JavaIsoVisitor<ExecutionContext> {

@Override
public J preVisit(J tree, ExecutionContext ctx) {
stopAfterPreVisit();
// Remove the JUnit 4 annotation where the Jupiter equivalent is already present, to avoid creating a
// duplicate annotation when the type is subsequently changed below.
doAfterVisit(new RemoveRedundantJUnit4LifecycleAnnotations());
JUNIT4_TO_JUPITER.forEach((from, to) -> doAfterVisit(new ChangeType(from, to, true).getVisitor()));
return tree;
}
@Override
public List<Recipe> getRecipeList() {
return JUNIT4_TO_JUPITER.entrySet().stream().map(e -> new ChangeType(e.getKey(), e.getValue(), true)).collect(toList());
}

private static class RemoveRedundantJUnit4LifecycleAnnotations extends JavaIsoVisitor<ExecutionContext> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.*;

import java.util.List;

import static java.util.Collections.singletonList;

public class UseWiremockExtension extends Recipe {

private static final String WIREMOCK_RULE = "com.github.tomakehurst.wiremock.junit.WireMockRule";
Expand All @@ -39,18 +43,14 @@ public class UseWiremockExtension extends Recipe {
@Getter
final String description = "As of 2.31.0, wiremock [supports JUnit 5](https://wiremock.org/docs/junit-jupiter/) via an extension.";

@Override
public List<Recipe> getRecipeList() {
return singletonList(new ChangeType(WIREMOCK_RULE, WIREMOCK_EXTENSION, true));
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>(WIREMOCK_RULE, false), new JavaVisitor<ExecutionContext>() {

@Override
public J preVisit(J tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
doAfterVisit(new ChangeType(WIREMOCK_RULE, WIREMOCK_EXTENSION, true).getVisitor());
}
return tree;
}

@Override
public J visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
J.VariableDeclarations vd = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;

import java.util.List;

import static java.util.Collections.singletonList;

/**
* In Mockito 1 you use a code snippet like:
* <p>
Expand All @@ -44,20 +48,18 @@ public class MockUtilsToStatic extends Recipe {
@Getter
final String description = "Best-effort attempt to remove Mockito `MockUtil` instances.";

@Override
public List<Recipe> getRecipeList() {
return singletonList(new ChangeMethodTargetToStatic("org.mockito.internal.util.MockUtil *(..)", "org.mockito.internal.util.MockUtil", null, null, false));
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>("org.mockito.internal.util.MockUtil", false), new MockUtilsToStaticVisitor());
}

public static class MockUtilsToStaticVisitor extends JavaVisitor<ExecutionContext> {
private static final MethodMatcher METHOD_MATCHER = new MethodMatcher("org.mockito.internal.util.MockUtil <constructor>()");
private final ChangeMethodTargetToStatic changeMethodTargetToStatic = new ChangeMethodTargetToStatic("org.mockito.internal.util.MockUtil *(..)", "org.mockito.internal.util.MockUtil", null, null, false);

@Override
public J visitCompilationUnit(J.CompilationUnit compilationUnit, ExecutionContext ctx) {
J.CompilationUnit cu = (J.CompilationUnit) super.visitCompilationUnit(compilationUnit, ctx);
return (J.CompilationUnit) changeMethodTargetToStatic.getVisitor().visitNonNull(cu, ctx);
}

@Override
public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.RemoveUnusedImports;
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.java.tree.TypeUtils;

import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -159,7 +159,7 @@ public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations
if (value instanceof J.Lambda || value instanceof J.Case && ((J.Case) value).getStatements().isEmpty()) {
return mi;
}
doAfterVisit(new RemoveUnusedImports().getVisitor());
typesReferencedBy(mi).forEach(this::maybeRemoveImport);
return null;
}
return mi;
Expand Down Expand Up @@ -215,4 +215,18 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Atomi
}
);
}

private static Set<String> typesReferencedBy(J tree) {
return new JavaIsoVisitor<Set<String>>() {
@Override
public @Nullable JavaType visitType(@Nullable JavaType javaType, Set<String> types) {
JavaType owner = javaType instanceof JavaType.Method ? ((JavaType.Method) javaType).getDeclaringType() : javaType instanceof JavaType.Variable ? ((JavaType.Variable) javaType).getOwner() : javaType;
JavaType.FullyQualified type = TypeUtils.asFullyQualified(owner);
if (type != null) {
types.add(type.getFullyQualifiedName());
}
return javaType;
}
}.reduce(tree, new HashSet<>());
}
}
Loading