Skip to content
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

Add recipes to migrate from TestNG to AssertJ #520

Merged
merged 18 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ dependencies {
implementation("org.openrewrite:rewrite-maven")
implementation("org.openrewrite.recipe:rewrite-java-dependencies:$rewriteVersion")
implementation("org.openrewrite.recipe:rewrite-static-analysis:$rewriteVersion")
implementation("org.openrewrite.recipe:rewrite-third-party:$rewriteVersion") {
// TODO remove once available from https://github.com/openrewrite/rewrite-third-party/commit/474b3461cdae4bcbd80
exclude(module = "jakarta.xml.bind-api")
}
runtimeOnly("org.openrewrite:rewrite-java-17")

compileOnly("org.projectlombok:lombok:latest.release")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* 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.assertj.testng;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
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.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.util.List;

public class TestNgAssertEqualsToAssertThat
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
extends Recipe {

@Override
public String getDisplayName() {
return "TestNG `assertEquals` to AssertJ";
}

@Override
public String getDescription() {
return "Convert TestNG-style `assertEquals()` to AssertJ's `assertThat().isEqualTo()`.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>("org.testng.Assert", false), new AssertEqualsToAssertThatVisitor());
}

public static class AssertEqualsToAssertThatVisitor extends JavaIsoVisitor<ExecutionContext> {
private JavaParser.Builder<?, ?> assertionsParser;

private JavaParser.Builder<?, ?> assertionsParser(ExecutionContext ctx) {
if (assertionsParser == null) {
assertionsParser = JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "assertj-core-3.24");
}
return assertionsParser;
}

private static final MethodMatcher TESTNG_ASSERT_EQUALS = new MethodMatcher("org.testng.Assert" + " assertEquals(..)");

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (!TESTNG_ASSERT_EQUALS.matches(method)) {
return method;
}

List<Expression> args = method.getArguments();
Expression expected = args.get(1);
Expression actual = args.get(0);

//always add the import (even if not referenced)
maybeAddImport("org.assertj.core.api.Assertions", "assertThat", false);

// Remove import for "org.testng.Assert" if no longer used.
maybeRemoveImport("org.testng.Assert");

if (args.size() == 2) {
return JavaTemplate.builder("assertThat(#{any()}).isEqualTo(#{any()});")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should it rewrite to hasSameElementsAs for Set?

    @Test
    public void test()
    {
        Set<Integer> actual = com.google.common.collect.ImmutableSortedSet.of(2, 1);
        Set<Integer> expected =  com.google.common.collect.ImmutableSet.of(2, 1);
        org.testng.Assert.assertEquals(actual, expected);
        org.assertj.core.api.Assertions.assertThat(actual).hasSameElementsAs(expected);
        org.assertj.core.api.Assertions.assertThat(actual).isEqualTo(expected); // fails with
        // java.lang.AssertionError:
        // expected: [2, 1]
        //  but was: [1, 2]
        // when comparing elements using Ordering.natural()
    }

.staticImports("org.assertj.core.api.Assertions.assertThat")
.javaParser(assertionsParser(ctx))
.build()
.apply(getCursor(), method.getCoordinates().replace(), actual, expected);
} else if (args.size() == 3 && !isFloatingPointType(args.get(2))) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like when args.get(2) is 0 then isFloatingPointType does not properly resolve type
assertEquals(Float.MAX_VALUE, config.getFloatOption(), 0);
->
assertThat(Float.MAX_VALUE).as(0).isEqualTo(config.getFloatOption());

https://github.com/airlift/airlift/pull/1194/files#diff-f4ec6d967f355397849228565bddf5982dbcfc629ec05b6cf8f4e5cfb68ba700R190

Expression message = args.get(2);
JavaTemplate.Builder template = TypeUtils.isString(message.getType()) ?
JavaTemplate.builder("assertThat(#{any()}).as(#{any(String)}).isEqualTo(#{any()});") :
JavaTemplate.builder("assertThat(#{any()}).as(#{any(java.util.function.Supplier)}).isEqualTo(#{any()});");
return template
.staticImports("org.assertj.core.api.Assertions.assertThat")
.imports("java.util.function.Supplier")
.javaParser(assertionsParser(ctx))
.build()
.apply(
getCursor(),
method.getCoordinates().replace(),
actual,
message,
expected
);
} else if (args.size() == 3) {
//always add the import (even if not referenced)
maybeAddImport("org.assertj.core.api.Assertions", "within", false);
return JavaTemplate.builder("assertThat(#{any()}).isCloseTo(#{any()}, within(#{any()}));")
Copy link
Contributor Author

@ssheikin ssheikin Jun 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for
assertEquals(digest.valueAt(0), value, 0.001f);
it generates
assertThat(digest.valueAt(0)).isCloseTo(value, within(0.001f));
which does not compile, because previously float was implicitly converted to double
It has to be
assertThat(digest.valueAt(0)).isCloseTo(value, within(0.001));
airlift/airlift@7f935b3 (#1194)

.staticImports("org.assertj.core.api.Assertions.assertThat", "org.assertj.core.api.Assertions.within")
.javaParser(assertionsParser(ctx))
.build()
.apply(getCursor(), method.getCoordinates().replace(), actual, expected, args.get(2));

}

// The assertEquals is using a floating point with a delta argument and a message.
Expression message = args.get(3);

//always add the import (even if not referenced)
maybeAddImport("org.assertj.core.api.Assertions", "within", false);
JavaTemplate.Builder template = TypeUtils.isString(message.getType()) ?
JavaTemplate.builder("assertThat(#{any()}).as(#{any(String)}).isCloseTo(#{any()}, within(#{any()}));") :
JavaTemplate.builder("assertThat(#{any()}).as(#{any(java.util.function.Supplier)}).isCloseTo(#{any()}, within(#{any()}));");
return template
.staticImports("org.assertj.core.api.Assertions.assertThat", "org.assertj.core.api.Assertions.within")
.imports("java.util.function.Supplier")
.javaParser(assertionsParser(ctx))
.build()
.apply(
getCursor(),
method.getCoordinates().replace(),
actual,
message,
expected,
args.get(2)
);
}

private static boolean isFloatingPointType(Expression expression) {

JavaType.FullyQualified fullyQualified = TypeUtils.asFullyQualified(expression.getType());
if (fullyQualified != null) {
String typeName = fullyQualified.getFullyQualifiedName();
return "java.lang.Double".equals(typeName) || "java.lang.Float".equals(typeName);
}

JavaType.Primitive parameterType = TypeUtils.asPrimitive(expression.getType());
return parameterType == JavaType.Primitive.Double || parameterType == JavaType.Primitive.Float;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* 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.assertj.testng;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
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.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.TypeUtils;

import java.util.List;

public class TestNgAssertFalseToAssertThat
extends Recipe {

@Override
public String getDisplayName() {
return "TestNG `assertFalse` to AssertJ";
}

@Override
public String getDescription() {
return "Convert TestNG-style `assertFalse()` to AssertJ's `assertThat().isFalse()`.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>("org.testng.Assert", false), new AssertFalseToAssertThatVisitor());
}

public static class AssertFalseToAssertThatVisitor extends JavaIsoVisitor<ExecutionContext> {
private JavaParser.Builder<?, ?> assertionsParser;

private JavaParser.Builder<?, ?> assertionsParser(ExecutionContext ctx) {
if (assertionsParser == null) {
assertionsParser = JavaParser.fromJavaVersion()
.classpathFromResources(ctx, "assertj-core-3.24");
}
return assertionsParser;
}

private static final MethodMatcher TESTNG_ASSERT_FALSE = new MethodMatcher("org.testng.Assert" + " assertFalse(boolean, ..)");

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
if (!TESTNG_ASSERT_FALSE.matches(method)) {
return method;
}

List<Expression> args = method.getArguments();
Expression actual = args.get(0);

if (args.size() == 1) {
method = JavaTemplate.builder("assertThat(#{any(boolean)}).isFalse();")
.staticImports("org.assertj.core.api.Assertions.assertThat")
.javaParser(assertionsParser(ctx))
.build()
.apply(
getCursor(),
method.getCoordinates().replace(),
actual
);
} else {
Expression message = args.get(1);
JavaTemplate.Builder template = TypeUtils.isString(message.getType()) ?
JavaTemplate.builder("assertThat(#{any(boolean)}).as(#{any(String)}).isFalse();") :
JavaTemplate.builder("assertThat(#{any(boolean)}).as(#{any(java.util.function.Supplier)}).isFalse();");

method = template
.staticImports("org.assertj.core.api.Assertions.assertThat")
.javaParser(assertionsParser(ctx))
.build()
.apply(
getCursor(),
method.getCoordinates().replace(),
actual,
message
);
}

//Make sure there is a static import for "org.assertj.core.api.Assertions.assertThat" (even if not referenced)
maybeAddImport("org.assertj.core.api.Assertions", "assertThat", false);

// Remove import for "org.testng.Assert" if no longer used.
maybeRemoveImport("org.testng.Assert");

return method;
}
}
}
Loading