Skip to content

Commit

Permalink
Refactor assertEquals(<boolean>, ...) and `assertNotEquals(<boolean…
Browse files Browse the repository at this point in the history
…>, ...)` to `assertTrue` or `assertFalse`
  • Loading branch information
ammachado committed Oct 24, 2023
1 parent 22dfa7e commit 4ace42e
Show file tree
Hide file tree
Showing 5 changed files with 424 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.testing.cleanup;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;

public class AssertEqualsBooleanToAssertBoolean extends Recipe {
private static final MethodMatcher ASSERT_EQUALS = new MethodMatcher(
"org.junit.jupiter.api.Assertions assertEquals(..)");

@Override
public String getDisplayName() {
return "Replace JUnit `assertEquals(false, <boolean>)` to `assertFalse(<boolean>)` / `assertTrue(<boolean>)`";
}

@Override
public String getDescription() {
return "Using `assertFalse` or `assertTrue` is simpler and more clear.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaVisitor<ExecutionContext>() {

JavaParser.Builder<?, ?> javaParser = null;

private JavaParser.Builder<?, ?> javaParser(ExecutionContext ctx) {
if (javaParser == null) {
javaParser = JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5.9");
}
return javaParser;
}

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (ASSERT_EQUALS.matches(mi) && isBooleanLiteral(mi)) {
StringBuilder sb = new StringBuilder();
String assertMethod = Boolean.parseBoolean(((J.Literal) mi.getArguments().get(0)).getValueSource())
? "assertTrue" : "assertFalse";
Statement assertion = (Statement) mi.getArguments().get(1);
if (mi.getSelect() == null) {
maybeRemoveImport("org.junit.jupiter.api.Assertions");
maybeAddImport("org.junit.jupiter.api.Assertions", assertMethod);
} else {
sb.append("Assertions.");
}
sb.append("#{}(#{any(java.lang.Boolean)}");
Object[] args;
if (mi.getArguments().size() == 3) {
args = new Object[]{assertMethod, assertion, mi.getArguments().get(2)};
sb.append(", #{any()}");
} else {
args = new Object[]{assertMethod, mi.getArguments().get(1)};
}
sb.append(")");
JavaTemplate t;
if (mi.getSelect() == null) {
t = JavaTemplate.builder(sb.toString())
.contextSensitive()
.staticImports(String.format("org.junit.jupiter.api.Assertions.%s", assertMethod))
.javaParser(javaParser(ctx))
.build();
} else {
t = JavaTemplate.builder(sb.toString())
.contextSensitive()
.imports(String.format("org.junit.jupiter.api.Assertions.%s", assertMethod))
.javaParser(javaParser(ctx))
.build();
}
return t.apply(updateCursor(mi), mi.getCoordinates().replace(), args);
}
return mi;
}

private boolean isBooleanLiteral(J.MethodInvocation method) {
if (!method.getArguments().isEmpty() && method.getArguments().get(0) instanceof J.Literal) {
J.Literal literal = (J.Literal) method.getArguments().get(0);
return JavaType.Primitive.Boolean.equals(literal.getType());
}

return false;
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.testing.cleanup;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Statement;

public class AssertNotEqualsBooleanToAssertBoolean extends Recipe {
private static final MethodMatcher ASSERT_NOT_EQUALS = new MethodMatcher(
"org.junit.jupiter.api.Assertions assertNotEquals(..)");

@Override
public String getDisplayName() {
return "Replace JUnit `assertNotEquals(false, <boolean>)` to `assertFalse(<boolean>)` / `assertTrue(<boolean>)`";
}

@Override
public String getDescription() {
return "Using `assertFalse` or `assertTrue` is simpler and more clear.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaVisitor<ExecutionContext>() {

JavaParser.Builder<?, ?> javaParser = null;

private JavaParser.Builder<?, ?> javaParser(ExecutionContext ctx) {
if (javaParser == null) {
javaParser = JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "junit-jupiter-api-5.9");
}
return javaParser;
}

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (ASSERT_NOT_EQUALS.matches(mi) && isBooleanLiteral(mi)) {
StringBuilder sb = new StringBuilder();
String assertMethod = Boolean.parseBoolean(((J.Literal) mi.getArguments().get(0)).getValueSource())
? "assertFalse" : "assertTrue";
Statement assertion = (Statement) mi.getArguments().get(1);
if (mi.getSelect() == null) {
maybeRemoveImport("org.junit.jupiter.api.Assertions");
maybeAddImport("org.junit.jupiter.api.Assertions", assertMethod);
} else {
sb.append("Assertions.");
}
sb.append("#{}(#{any(java.lang.Boolean)}");
Object[] args;
if (mi.getArguments().size() == 3) {
args = new Object[]{assertMethod, assertion, mi.getArguments().get(2)};
sb.append(", #{any()}");
} else {
args = new Object[]{assertMethod, mi.getArguments().get(1)};
}
sb.append(")");
JavaTemplate t;
if (mi.getSelect() == null) {
t = JavaTemplate.builder(sb.toString())
.contextSensitive()
.staticImports(String.format("org.junit.jupiter.api.Assertions.%s", assertMethod))
.javaParser(javaParser(ctx))
.build();
} else {
t = JavaTemplate.builder(sb.toString())
.contextSensitive()
.imports(String.format("org.junit.jupiter.api.Assertions.%s", assertMethod))
.javaParser(javaParser(ctx))
.build();
}
return t.apply(updateCursor(mi), mi.getCoordinates().replace(), args);
}
return mi;
}

private boolean isBooleanLiteral(J.MethodInvocation method) {
if (!method.getArguments().isEmpty() && method.getArguments().get(0) instanceof J.Literal) {
J.Literal literal = (J.Literal) method.getArguments().get(0);
return JavaType.Primitive.Boolean.equals(literal.getType());
}

return false;
}
};
}
}
2 changes: 2 additions & 0 deletions src/main/resources/META-INF/rewrite/junit5.yml
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,8 @@ recipeList:
- org.openrewrite.java.testing.cleanup.AssertFalseEqualsToAssertNotEquals
- org.openrewrite.java.testing.cleanup.AssertEqualsNullToAssertNull
- org.openrewrite.java.testing.cleanup.AssertFalseNullToAssertNotNull
- org.openrewrite.java.testing.cleanup.AssertEqualsBooleanToAssertBoolean
- org.openrewrite.java.testing.cleanup.AssertNotEqualsBooleanToAssertBoolean
- org.openrewrite.java.testing.cleanup.AssertionsArgumentOrder
---
type: specs.openrewrite.org/v1beta/recipe
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* Copyright 2021 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.testing.cleanup;

import org.junit.jupiter.api.Test;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.Issue;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;

class AssertEqualsBooleanToAssertBooleanTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec
.parser(JavaParser.fromJavaVersion().classpathFromResources(new InMemoryExecutionContext(), "junit-jupiter-api-5.9"))
.recipe(new AssertEqualsBooleanToAssertBoolean());
}

@SuppressWarnings({"ConstantConditions"})
@Test
void assertEqualsFalseToToAssertFalse() {
//language=java
rewriteRun(
java(
"""
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Test {
void test() {
String a = "a";
String c = "c";
assertEquals(false, a.equals(c));
assertEquals(false, a.equals(c), "message");
}
}
""",
"""
import static org.junit.jupiter.api.Assertions.assertFalse;
public class Test {
void test() {
String a = "a";
String c = "c";
assertFalse(a.equals(c));
assertFalse(a.equals(c), "message");
}
}
"""
)
);
}

@Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/206")
@SuppressWarnings({"ConstantConditions", "SimplifiableAssertion"})
@Test
void preserveStyleOfStaticImportOrNot() {
//language=java
rewriteRun(
java(
"""
import org.junit.jupiter.api.Assertions;
public class Test {
void test() {
String a = "a";
String c = "c";
Assertions.assertEquals(false, a.equals(c), "message");
}
}
""",
"""
import org.junit.jupiter.api.Assertions;
public class Test {
void test() {
String a = "a";
String c = "c";
Assertions.assertFalse(a.equals(c), "message");
}
}
"""
)
);
}
}
Loading

0 comments on commit 4ace42e

Please sign in to comment.