Skip to content

ExpectedExceptionToAssertThrows: Handle branching and var usage in except methods #721

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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 @@ -15,20 +15,25 @@
*/
package org.openrewrite.java.testing.junit5;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.*;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;
import org.openrewrite.staticanalysis.LambdaBlockToExpression;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

import static java.util.Collections.emptyList;
import static org.openrewrite.Tree.randomId;

/**
* Replace usages of JUnit 4's @Rule ExpectedException with JUnit 5 Assertions.
Expand Down Expand Up @@ -61,6 +66,18 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {

private static class ExpectedExceptionToAssertThrowsVisitor extends JavaIsoVisitor<ExecutionContext> {

private static final String FIRST_EXPECTED_EXCEPTION_METHOD_INVOCATION = "firstExpectedExceptionMethodInvocation";
private static final String STATEMENTS_AFTER_EXPECT_EXCEPTION = "statementsAfterExpectException";
private static final String HAS_MATCHER = "hasMatcher";
private static final String EXCEPTION_CLASS = "exceptionClass";

private static final MethodMatcher EXPECTED_EXCEPTION_ALL_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expect*(..)");
private static final MethodMatcher EXPECTED_EXCEPTION_CLASS_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expect(java.lang.Class)");
private static final MethodMatcher EXPECTED_MESSAGE_STRING_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expectMessage(java.lang.String)");
private static final MethodMatcher EXPECTED_MESSAGE_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expectMessage(org.hamcrest.Matcher)");
private static final MethodMatcher EXPECTED_EXCEPTION_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expect(org.hamcrest.Matcher)");
private static final MethodMatcher EXPECTED_EXCEPTION_CAUSE_MATCHER = new MethodMatcher("org.junit.rules.ExpectedException expectCause(org.hamcrest.Matcher)");

@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
Expand All @@ -77,192 +94,154 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex
}
return statement;
})));

doAfterVisit(new LambdaBlockToExpression().getVisitor());
return cd;
}

@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration methodDecl, ExecutionContext ctx) {
J.MethodDeclaration m = super.visitMethodDeclaration(methodDecl, ctx);

J.MethodInvocation expectMethodInvocation = getCursor().pollMessage("expectedExceptionMethodInvocation");
J.MethodInvocation expectMessageMethodInvocation = getCursor().pollMessage("expectedExceptionMethodMessageInvocation");
J.MethodInvocation expectCauseMethodInvocation = getCursor().pollMessage("expectCauseMethodInvocation");

if (expectMethodInvocation == null &&
expectMessageMethodInvocation == null &&
expectCauseMethodInvocation == null) {
return m;
}

assert m.getBody() != null;
J.Block bodyWithoutExpectedExceptionCalls = m.getBody().withStatements(ListUtils.map(m.getBody().getStatements(),
statement -> isExpectedExceptionMethodInvocation(statement) ? null : statement));

boolean isExpectArgAMatcher = false;
if (expectMethodInvocation != null) {
List<Expression> args = expectMethodInvocation.getArguments();
if (args.size() != 1) {
return m;
}

Expression expectMethodArg = args.get(0);
isExpectArgAMatcher = isHamcrestMatcher(expectMethodArg);
JavaType.FullyQualified argType = TypeUtils.asFullyQualified(expectMethodArg.getType());
if (!isExpectArgAMatcher && (argType == null || !"java.lang.Class".equals(argType.getFullyQualifiedName()))) {
return m;
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx);
if (getCursor().pollMessage("hasExpectException") != null) {
List<NameTree> thrown = m.getThrows();
if (thrown != null && !thrown.isEmpty()) {
assert m.getBody() != null;
return m.withBody(m.getBody().withPrefix(thrown.get(0).getPrefix())).withThrows(Collections.emptyList());
}
}
return m;
}

boolean isExpectMessageArgAMatcher = false;
if (expectMessageMethodInvocation != null) {
List<Expression> args = expectMessageMethodInvocation.getArguments();
if (args.size() != 1) {
return m;
}

final Expression expectMessageMethodArg = args.get(0);
isExpectMessageArgAMatcher = isHamcrestMatcher(expectMessageMethodArg);
if (!isExpectMessageArgAMatcher && !TypeUtils.isString(expectMessageMethodArg.getType())) {
return m;
}
@Override
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
J.Block b = super.visitBlock(block, ctx);
List<Statement> statementsAfterExpectException = getCursor().pollMessage(STATEMENTS_AFTER_EXPECT_EXCEPTION);
if (statementsAfterExpectException == null) {
return b;
}

boolean isExpectedCauseArgAMatcher = false;
if (expectCauseMethodInvocation != null) {
List<Expression> args = expectCauseMethodInvocation.getArguments();
if (args.size() != 1) {
return m;
}

final Expression expectCauseMethodArg = args.get(0);
isExpectedCauseArgAMatcher = isHamcrestMatcher(expectCauseMethodArg);
if (!isExpectedCauseArgAMatcher) {
return m;
}
J.Block statementsAfterExpectExceptionBlock = new J.Block(randomId(), Space.EMPTY,
Markers.EMPTY, new JRightPadded<>(false, Space.EMPTY, Markers.EMPTY),
emptyList(), Space.format(" ")).withStatements(statementsAfterExpectException);
String exceptionDeclParam = getCursor().pollMessage(HAS_MATCHER) != null ? "Throwable exception = " : "";
Object exceptionClass = getCursor().pollMessage(EXCEPTION_CLASS);
if (exceptionClass == null) {
exceptionClass = "Exception.class";
}

String exceptionDeclParam = ((isExpectArgAMatcher || isExpectMessageArgAMatcher || isExpectedCauseArgAMatcher) ||
expectMessageMethodInvocation != null) ?
"Throwable exception = " : "";

Object expectedExceptionParam = (expectMethodInvocation == null || isExpectArgAMatcher) ?
"Exception.class" : expectMethodInvocation.getArguments().get(0);

String templateString = expectedExceptionParam instanceof String ? "#{}assertThrows(#{}, () -> #{any()});" : "#{}assertThrows(#{any()}, () -> #{any()});";
m = JavaTemplate.builder(templateString)
maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows", false);
Statement firstExpectedExceptionMethodInvocation = getCursor().getMessage(FIRST_EXPECTED_EXCEPTION_METHOD_INVOCATION);
String templateString = exceptionClass instanceof String ? "#{}assertThrows(#{}, () -> #{any()});" : "#{}assertThrows(#{any()}, () -> #{any()});";
b = JavaTemplate.builder(templateString)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3"))
.staticImports("org.junit.jupiter.api.Assertions.assertThrows")
.build()
.apply(
updateCursor(m),
m.getCoordinates().replaceBody(),
updateCursor(b),
firstExpectedExceptionMethodInvocation.getCoordinates().before(),
exceptionDeclParam,
expectedExceptionParam,
bodyWithoutExpectedExceptionCalls
exceptionClass,
statementsAfterExpectExceptionBlock
);

// Clear out any declared thrown exceptions
List<NameTree> thrown = m.getThrows();
if (thrown != null && !thrown.isEmpty()) {
assert m.getBody() != null;
m = m.withBody(m.getBody().withPrefix(thrown.get(0).getPrefix())).withThrows(Collections.emptyList());
}

// Unconditionally add the import for assertThrows, got a report where the above template adds the method successfully
// but with missing type attribution for assertThrows so the import was missing
maybeAddImport("org.junit.jupiter.api.Assertions", "assertThrows", false);

if (expectMessageMethodInvocation != null && !isExpectMessageArgAMatcher && m.getBody() != null) {
m = JavaTemplate.builder("assertTrue(exception.getMessage().contains(#{any(java.lang.String)}));")
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3"))
.staticImports("org.junit.jupiter.api.Assertions.assertTrue")
.build()
.apply(
updateCursor(m),
m.getBody().getCoordinates().lastStatement(),
expectMessageMethodInvocation.getArguments().get(0)
);
maybeAddImport("org.junit.jupiter.api.Assertions", "assertTrue");
}

JavaTemplate assertThatTemplate = JavaTemplate.builder("assertThat(#{}, #{any()});")
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3"))
.staticImports("org.hamcrest.MatcherAssert.assertThat")
.build();

assert m.getBody() != null;
if (isExpectArgAMatcher) {
m = assertThatTemplate.apply(updateCursor(m), m.getBody().getCoordinates().lastStatement(),
"exception", expectMethodInvocation.getArguments().get(0));
maybeAddImport("org.hamcrest.MatcherAssert", "assertThat");
}

assert m.getBody() != null;
if (isExpectMessageArgAMatcher) {
m = assertThatTemplate.apply(updateCursor(m), m.getBody().getCoordinates().lastStatement(),
"exception.getMessage()", expectMessageMethodInvocation.getArguments().get(0));
maybeAddImport("org.hamcrest.MatcherAssert", "assertThat");
}

assert m.getBody() != null;
if (isExpectedCauseArgAMatcher) {
m = assertThatTemplate.apply(updateCursor(m), m.getBody().getCoordinates().lastStatement(),
"exception.getCause()", expectCauseMethodInvocation.getArguments().get(0));
maybeAddImport("org.hamcrest.MatcherAssert", "assertThat");
Cursor updateCursor = updateCursor(b);
AtomicBoolean removeStatement = new AtomicBoolean(false);
J.Identifier exceptionIdentifier = new J.Identifier(Tree.randomId(),
Space.EMPTY,
Markers.EMPTY,
emptyList(),
"exception",
JavaType.ShallowClass.build("java.lang.Throwable"),
null);
b = b.withStatements(ListUtils.map(b.getStatements(), statement -> {
if (statement instanceof J.MethodInvocation) {
if (EXPECTED_EXCEPTION_ALL_MATCHER.matches((J.MethodInvocation) statement)) {
removeStatement.set(true);
return getExpectExceptionTemplate((J.MethodInvocation) statement, ctx)
.<J.MethodInvocation>map(t -> t.apply(
new Cursor(updateCursor, statement),
statement.getCoordinates().replace(), exceptionIdentifier,
((J.MethodInvocation) statement).getArguments().get(0)))
.orElse(null);
}
}
return removeStatement.get() ? null : 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);
return b.withStatements(ListUtils.concat(b.getStatements(), returnStatement));
}

doAfterVisit(new LambdaBlockToExpression().getVisitor());

return m;
return b;
}

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (method.getMethodType() != null && "org.junit.rules.ExpectedException".equals(method.getMethodType().getDeclaringType().getFullyQualifiedName())) {
switch (method.getSimpleName()) {
case "expect":
getCursor().putMessageOnFirstEnclosing(J.MethodDeclaration.class, "expectedExceptionMethodInvocation", method);
break;
case "expectMessage":
getCursor().putMessageOnFirstEnclosing(J.MethodDeclaration.class, "expectedExceptionMethodMessageInvocation", method);
break;
case "expectCause":
getCursor().putMessageOnFirstEnclosing(J.MethodDeclaration.class, "expectCauseMethodInvocation", method);
break;
}
if (!EXPECTED_EXCEPTION_ALL_MATCHER.matches(method)) {
return method;
}
getCursor().dropParentUntil(J.MethodDeclaration.class::isInstance).putMessage("hasExpectException", true );
getCursor().dropParentUntil(J.Block.class::isInstance).computeMessageIfAbsent(FIRST_EXPECTED_EXCEPTION_METHOD_INVOCATION, k -> method);
List<Statement> successorStatements = findSuccessorStatements(getCursor());
getCursor().putMessageOnFirstEnclosing(J.Block.class, STATEMENTS_AFTER_EXPECT_EXCEPTION, successorStatements);
if (EXPECTED_EXCEPTION_CLASS_MATCHER.matches(method)) {
getCursor().putMessageOnFirstEnclosing(J.Block.class, EXCEPTION_CLASS, method.getArguments().get(0));
} else {
getCursor().putMessageOnFirstEnclosing(J.Block.class, HAS_MATCHER, true);
}
return method;
}

private boolean isHamcrestMatcher(J j) {
if (!(j instanceof J.MethodInvocation)) {
return false;
/**
* From the current cursor point find all the next statements that can be executed in the current path.
*/
private List<Statement> findSuccessorStatements(Cursor cursor) {
if (cursor.firstEnclosing(J.MethodDeclaration.class) == null) {
return Collections.emptyList();
}

final J.MethodInvocation method = (J.MethodInvocation) j;
return method.getArguments().size() == 1 &&
method.getMethodType() != null &&
TypeUtils.isOfClassType(method.getMethodType().getDeclaringType(), "org.hamcrest.Matchers");
List<Statement> successorStatements = new ArrayList<>();
Cursor cursorJustBeforeBlock = getCursor();
while (!(cursor.getValue() instanceof J.MethodDeclaration)) {
if (!(cursor.getValue() instanceof J.Block)) {
cursorJustBeforeBlock = cursor;
cursor = cursor.getParentTreeCursor();
continue;
}
J.Block block = cursor.getValue();
boolean found = false;
for (Statement statement : block.getStatements()) {
if (found) {
successorStatements.add(statement);
} else if (statement == cursorJustBeforeBlock.getValue()) {
found = true;
}
}
cursor = cursor.getParentTreeCursor();
}
return successorStatements;
}

private static boolean isExpectedExceptionMethodInvocation(Statement statement) {
if (!(statement instanceof J.MethodInvocation)) {
return false;
private Optional<JavaTemplate> getExpectExceptionTemplate(J.MethodInvocation method, ExecutionContext ctx) {
String template = null;
if (EXPECTED_MESSAGE_STRING_MATCHER.matches(method)) {
maybeAddImport("org.hamcrest.CoreMatchers", "containsString");
template = "assertThat(#{any(java.lang.Throwable)}.getMessage(), containsString(#{any(java.lang.String)}))";
} else if (EXPECTED_MESSAGE_MATCHER.matches(method)) {
template = "assertThat(#{any(java.lang.Throwable)}.getMessage(), #{any(org.hamcrest.Matcher)})";
} else if (EXPECTED_EXCEPTION_MATCHER.matches(method)) {
template = "assertThat(#{any(java.lang.Throwable)}, #{any(org.hamcrest.Matcher)})";
} else if (EXPECTED_EXCEPTION_CAUSE_MATCHER.matches(method)) {
template = "assertThat(#{any(java.lang.Throwable)}.getCause(), #{any(org.hamcrest.Matcher)})";
}

J.MethodInvocation m = (J.MethodInvocation) statement;
if (m.getMethodType() == null) {
return false;
if (template == null) {
return Optional.empty();
}
maybeAddImport("org.hamcrest.MatcherAssert", "assertThat");
return Optional.of(JavaTemplate.builder(template).contextSensitive()
.javaParser(JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5", "hamcrest-3"))
.staticImports("org.hamcrest.MatcherAssert.assertThat", "org.hamcrest.CoreMatchers.containsString")
.build());

return TypeUtils.isOfClassType(m.getMethodType().getDeclaringType(), "org.junit.rules.ExpectedException");
}
}
}
Loading