Skip to content

Commit

Permalink
Merge branch 'main' into issue-373
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek authored Dec 10, 2023
2 parents b5f9f0c + e383281 commit 0f3736d
Show file tree
Hide file tree
Showing 85 changed files with 5,161 additions and 1,283 deletions.
20 changes: 0 additions & 20 deletions .github/workflows/dependency-check.yml

This file was deleted.

4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@
This project implements a [Rewrite module](https://github.com/openrewrite/rewrite) that performs common Java testing migration tasks, like migrating from JUnit 4 to JUnit 5.

Browse [a selection of recipes available through this module in the recipe catalog](https://docs.openrewrite.org/recipes/java/testing).

## Contributing

We appreciate all types of contributions. See the [contributing guide](https://github.com/openrewrite/.github/blob/main/CONTRIBUTING.md) for detailed instructions on how to get started.
7 changes: 7 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ recipeDependencies {
parserClasspath("com.github.tomakehurst:wiremock-jre8:2.35.0")
parserClasspath("org.mockito:mockito-all:1.10.19")
parserClasspath("org.mockito:mockito-core:3.+")
parserClasspath("org.jmockit:jmockit:1.49")
parserClasspath("org.mockito:mockito-junit-jupiter:3.+")
parserClasspath("org.powermock:powermock-api-mockito:1.7.+")
parserClasspath("org.powermock:powermock-core:1.7.+")
Expand All @@ -38,11 +39,17 @@ dependencies {
compileOnly("org.projectlombok:lombok:latest.release")
annotationProcessor("org.projectlombok:lombok:latest.release")

implementation("org.testcontainers:testcontainers:latest.release")

testImplementation("org.openrewrite:rewrite-java-17")
testImplementation("org.openrewrite:rewrite-groovy")

testRuntimeOnly("org.gradle:gradle-tooling-api:latest.release")

testRuntimeOnly("com.tngtech.archunit:archunit:0.23.1")
testRuntimeOnly("org.testcontainers:testcontainers:latest.release")
testRuntimeOnly("org.testcontainers:nginx:latest.release")

// testImplementation("org.hamcrest:hamcrest:latest.release")
// testImplementation("org.assertj:assertj-core:latest.release")
}
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
29 changes: 17 additions & 12 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -133,26 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -197,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
/*
* Copyright 2023 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;

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.UsesMethod;
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 org.openrewrite.staticanalysis.SimplifyDurationCreationUnits;

import java.util.*;

public class AdoptAssertJDurationAssertions extends Recipe {

static final String DURATION_ASSERT_HAS_LONG = "org.assertj.core.api.AbstractDurationAssert has*(long)";

static final String INTEGER_ASSERT_IS_EQUAL_TO = "org.assertj.core.api.AbstractIntegerAssert isEqualTo(..)";
static final String INTEGER_ASSERT_IS_GREATER_THAN = "org.assertj.core.api.AbstractIntegerAssert isGreaterThan(..)";
static final String INTEGER_ASSERT_IS_LESS_THAN = "org.assertj.core.api.AbstractIntegerAssert isLessThan(..)";

static final String LONG_ASSERT_IS_LESS_THAN = "org.assertj.core.api.AbstractLongAssert isLessThan(..)";
static final String LONG_ASSERT_IS_GREATER_THAN = "org.assertj.core.api.AbstractLongAssert isGreaterThan(..)";
static final String LONG_ASSERT_IS_EQUAL_TO = "org.assertj.core.api.AbstractLongAssert isEqualTo(..)";

@Override
public String getDisplayName() {
return "Adopt AssertJ Duration assertions";
}

@Override
public String getDescription() {
return "Adopt AssertJ `DurationAssert` assertions for more expressive messages.";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(Preconditions.or(
new UsesMethod<>(DURATION_ASSERT_HAS_LONG, true),

new UsesMethod<>(INTEGER_ASSERT_IS_EQUAL_TO, true),
new UsesMethod<>(INTEGER_ASSERT_IS_GREATER_THAN, true),
new UsesMethod<>(INTEGER_ASSERT_IS_LESS_THAN, true),

new UsesMethod<>(LONG_ASSERT_IS_EQUAL_TO, true),
new UsesMethod<>(LONG_ASSERT_IS_GREATER_THAN, true),
new UsesMethod<>(LONG_ASSERT_IS_LESS_THAN, true)
), new AdoptAssertJDurationAssertionsVisitor()
);
}

@SuppressWarnings("DataFlowIssue")
private static class AdoptAssertJDurationAssertionsVisitor extends JavaIsoVisitor<ExecutionContext> {
private static final MethodMatcher ASSERT_THAT_MATCHER = new MethodMatcher("org.assertj.core.api.Assertions assertThat(..)");
private static final MethodMatcher GET_NANO_MATCHER = new MethodMatcher("java.time.Duration getNano()");
private static final MethodMatcher GET_SECONDS_MATCHER = new MethodMatcher("java.time.Duration getSeconds()");
private static final MethodMatcher AS_MATCHER = new MethodMatcher("org.assertj.core.api.AbstractObjectAssert as(..)");
private static final MethodMatcher TIME_UNIT_MATCHERS = new MethodMatcher(DURATION_ASSERT_HAS_LONG, true);
private static final List<MethodMatcher> IS_MATCHERS = Arrays.asList(
new MethodMatcher(INTEGER_ASSERT_IS_EQUAL_TO, true),
new MethodMatcher(INTEGER_ASSERT_IS_GREATER_THAN, true),
new MethodMatcher(INTEGER_ASSERT_IS_LESS_THAN, true),

new MethodMatcher(LONG_ASSERT_IS_EQUAL_TO, true),
new MethodMatcher(LONG_ASSERT_IS_GREATER_THAN, true),
new MethodMatcher(LONG_ASSERT_IS_LESS_THAN, true)
);
private static final Map<String, String> METHOD_MAP = new HashMap<String, String>() {{
put("getSeconds", "hasSeconds");
put("getNano", "hasNanos");

put("hasNanos", "hasMillis");
put("hasMillis", "hasSeconds");
put("hasSeconds", "hasMinutes");
put("hasMinutes", "hasHours");
put("hasHours", "hasDays");

put("isGreaterThan", "isPositive");
put("isLessThan", "isNegative");
put("isEqualTo", "isZero");
}};

@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation mi = super.visitMethodInvocation(method, ctx);
if (TIME_UNIT_MATCHERS.matches(mi)) {
return simplifyTimeUnits(mi, ctx);
} else if (IS_MATCHERS.stream().anyMatch(matcher -> matcher.matches(mi))) {
return simplifyMultipleAssertions(mi, ctx);
}
return mi;
}

private J.MethodInvocation simplifyMultipleAssertions(J.MethodInvocation m, ExecutionContext ctx) {
Expression isEqualToArg = m.getArguments().get(0);
Expression select = m.getSelect();
List<Object> templateParameters = new ArrayList<>();
templateParameters.add(null);
Expression asDescription = null;

if (AS_MATCHER.matches(select)) {
asDescription = ((J.MethodInvocation) select).getArguments().get(0);
select = ((J.MethodInvocation) select).getSelect();
templateParameters.add(asDescription);
}

if (!ASSERT_THAT_MATCHER.matches(select)) {
return m;
}

Expression assertThatArgumentExpr = ((J.MethodInvocation) select).getArguments().get(0);
if (!(assertThatArgumentExpr instanceof J.MethodInvocation)) {
return m;
}
J.MethodInvocation assertThatArg = (J.MethodInvocation) assertThatArgumentExpr;

if (isZero(isEqualToArg) && checkIfRelatedToDuration(assertThatArg)) {
String formatted_template = formatTemplate("assertThat(#{any()}).%s();", m.getSimpleName(), asDescription);
templateParameters.set(0, assertThatArg);
return applyTemplate(ctx, m, formatted_template, templateParameters.toArray());
}

if (GET_NANO_MATCHER.matches(assertThatArg) || GET_SECONDS_MATCHER.matches(assertThatArg)) {
Expression assertThatArgSelect = assertThatArg.getSelect();
String methodName = assertThatArg.getSimpleName();
String formatted_template = formatTemplate("assertThat(#{any()}).%s(#{any()});", methodName, asDescription);
templateParameters.set(0, assertThatArgSelect);
templateParameters.add(isEqualToArg);

return applyTemplate(ctx, m, formatted_template, templateParameters.toArray());
}

return m;
}

private boolean isZero(Expression isEqualToArg) {
if (isEqualToArg instanceof J.Literal) {
J.Literal literal = (J.Literal) isEqualToArg;
return literal.getValue() instanceof Number && ((Number) literal.getValue()).longValue() == 0;
}
return false;
}

private J.MethodInvocation simplifyTimeUnits(J.MethodInvocation m, ExecutionContext ctx) {
Expression arg = m.getArguments().get(0);
Long argValue = SimplifyDurationCreationUnits.getConstantIntegralValue(arg);
if (argValue == null) {
return m;
}

List<Object> unitInfo = getUnitInfo(m.getSimpleName(), Math.toIntExact(argValue));
String methodName = (String) unitInfo.get(0);
int methodArg = (int) unitInfo.get(1);
if (!(m.getSimpleName().equals(methodName))) {
// update method invocation with new name and arg
String template = String.format("#{any()}.%s(%d)", methodName, methodArg);
return applyTemplate(ctx, m, template, m.getSelect());
}

return m;
}

private static List<Object> getUnitInfo(String name, int argValue) {
final int timeLength;
if (name.equals("hasSeconds") || name.equals("hasMinutes")) {
timeLength = 60;
} else if (name.equals("hasNanos") || name.equals("hasMillis")) {
timeLength = 1000;
} else if (name.equals("hasHours")) {
timeLength = 24;
} else {
return Arrays.asList(name, argValue);
}

if (argValue % timeLength == 0) {
String newName = METHOD_MAP.get(name);
return getUnitInfo(newName, argValue / timeLength);
} else {
// returning name, newArg
return Arrays.asList(name, argValue);
}
}

private J.MethodInvocation applyTemplate(ExecutionContext ctx, J.MethodInvocation m, String template, Object... parameters) {
J.MethodInvocation invocation = JavaTemplate.builder(template)
.contextSensitive()
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "assertj-core-3.24"))
.build()
.apply(getCursor(), m.getCoordinates().replace(), parameters);

// retain whitespace formatting
if (invocation.getPadding().getSelect() != null && m.getPadding().getSelect() != null) {
return invocation.getPadding()
.withSelect(
invocation.getPadding().getSelect()
.withAfter(m.getPadding().getSelect().getAfter())
);
}
return invocation;
}

private boolean checkIfRelatedToDuration(J.MethodInvocation argument) {
// assertThat(<selectMethod()>.<argument()>).isEqual(0)
if (argument.getSelect() != null) {
if (argument.getSelect() instanceof J.MethodInvocation) {
J.MethodInvocation selectMethod = (J.MethodInvocation) argument.getSelect();
return TypeUtils.isOfType(selectMethod.getType(), JavaType.buildType("java.time.Duration"));
}
}
return false;
}

@SuppressWarnings("ConstantValue")
private String formatTemplate(String template, String methodName, Object asDescriptionArg) {
String replacementMethod = METHOD_MAP.get(methodName);
if (asDescriptionArg == null) {
return String.format(template, replacementMethod);
}
StringBuilder newTemplate = new StringBuilder(template);
newTemplate.insert(newTemplate.indexOf(").") + 1, ".as(#{any()})");
return String.format(newTemplate.toString(), replacementMethod);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ && getCursor().getParentTreeCursor().getValue() instanceof J.Block) {
);
maybeAddImport("org.assertj.core.api.AssertionsForClassTypes", "assertThatExceptionOfType");
maybeRemoveImport("org.junit.jupiter.api.Assertions.assertThrows");
maybeRemoveImport("org.junit.jupiter.api.Assertions");
}
}
return mi;
Expand Down
Loading

0 comments on commit 0f3736d

Please sign in to comment.