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

Merge DataProvider migration recipe from MBoegers/migrate-testngtojupiter-rewrite #38

Draft
wants to merge 51 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
c4846ab
Add TestNG dependency, so it is available on the classpath for tests
Philzen Jun 6, 2024
09d1ee0
Implement TestNG → JUnit5 @Test annotation migration recipe with tests
Philzen Jun 6, 2024
a94d4f3
Fix extraneous import added when all usages are fully qualified
Philzen Jun 7, 2024
19b3099
Implement migration of expectedExceptionsMessageRegExp annotation att…
Philzen Jun 6, 2024
2f74be1
Implement migration of TestNG enabled = false to Junit5 @Disabled
Philzen Jun 7, 2024
d939333
Add general introductory text and Java 8 compatiblity badge
Philzen Jun 7, 2024
0b63586
Implement migration of TestNG @Test(description) to Junit5 @DisplayName
Philzen Jun 7, 2024
b2b006e
Implement migration of TestNG @Test(groups) to Junit5 @Tag
Philzen Jun 7, 2024
63a3572
Remove samples content
Philzen Jun 9, 2024
48532bf
Add build & usage writeup and remove unrelated content from template
Philzen Jun 17, 2024
f78a1a8
Add rewrite-testing-frameworks dependency (enables official recipes)
Philzen Jun 9, 2024
e57948c
Cook up basic recipe list including testing.junit5.AddMissingNested
Philzen Jun 8, 2024
374cf3d
Set up code coverage statistics
Philzen Jun 9, 2024
dcb19b1
[CI] Run Jacoco during `mvn verify` and upload XML output as artifact
Philzen Jun 9, 2024
855a52d
[CI] Activate dedicated Sonar GitHub action
Philzen Jun 9, 2024
3ec4c6b
Include code coverage badge
Philzen Jun 9, 2024
474c292
Make java parser instantiation thread safe and move to utils class
Philzen Jun 9, 2024
470db0f
Put common constant strings into static final variables
Philzen Jun 9, 2024
3059a88
Factor out post visitCompilationUnit visitor
Philzen Jun 10, 2024
4eaf295
Always modify instead of creating new when annotation type J.FieldAccess
Philzen Jun 10, 2024
79bb143
Implement migration of class-level `@Test` annotation to methods
Philzen Jun 11, 2024
ff1d555
Replace GitHub and SonarCloud badges with shields.io
Philzen Jun 11, 2024
305e89b
Move maven build action into Analyze workflow
Philzen Jun 12, 2024
c751669
Add list of annotation attributes that cannot be migrated (yet)
Philzen Jun 14, 2024
ed8c4f6
Avoid 'File encoding has not been set' maven warning, defining UTF-8
Philzen Jun 15, 2024
d89aaf1
Factor out complex J.* operations into Util classes
Philzen Jun 15, 2024
bc3ebcf
Remove redundant checks and return early wherever feasible
Philzen Jun 17, 2024
c583f94
Move repetitive Comparator declarations into Util class
Philzen Jun 17, 2024
68f70fe
Improvements on the template for maven users (#56)
ammachado Jun 20, 2024
3585aaf
Disable process-sources:copy goal
Philzen Jun 22, 2024
ac7b188
Add tests and dependency for Data Provider migration
MBoegers Apr 17, 2024
98177a0
Implement data provider migrations
MBoegers Apr 17, 2024
12f6372
Fix licence headers
MBoegers Apr 17, 2024
58c0050
Add Search Visitors for annotation usage
MBoegers Apr 18, 2024
acb321d
Use preconditions and annotation search
MBoegers Apr 18, 2024
f5e4fb2
Introduce search visitor for Annotation and helper to extract annotat…
MBoegers Apr 18, 2024
58a0641
Refactor to use helpers
MBoegers Apr 18, 2024
ae36444
remove unused method
MBoegers Apr 18, 2024
423b1e2
Move DataProvider recipe one package-level and rename helper
Philzen Jun 22, 2024
e70bbbb
Refactor MigrateDataProvider recipe, add javadoc to utilities
MBoegers Apr 22, 2024
d2e4e0b
Apply best practices
MBoegers Apr 24, 2024
13f1a8d
add packages to test files to fix import order
MBoegers Apr 26, 2024
bf07f9c
apply best practices
MBoegers Apr 26, 2024
7994e9e
Introduce JDK 8 compatibility
Philzen Jun 22, 2024
942895d
Make inner classes static
Philzen Jun 22, 2024
4c5fc0f
Fix trailing whitespace in text blocks
Philzen Jun 22, 2024
34390f1
Fix typos and remove undocumented JavaDoc tags
Philzen Jun 22, 2024
c098fa7
Remove unused methods
Philzen Jun 22, 2024
27d4d09
Convert helper class to non-instantiable enum utility class
Philzen Jun 22, 2024
a72cc39
Apply finality to variables and return early where appropriate
Philzen Jun 22, 2024
20f672e
Add MigrateDataProvider to recipe list
Philzen Jun 22, 2024
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
Prev Previous commit
Next Next commit
Put common constant strings into static final variables
Philzen committed Jun 22, 2024
commit 470db0f57ebff0dae32428c29c8616336aa9518b
Original file line number Diff line number Diff line change
@@ -39,56 +39,63 @@ public String getDisplayName() {

@Override
public String getDescription() {
return "Update usages of TestNG's `@org.testng.annotations.Test` annotation to JUnit 5's `@org.junit.jupiter.api.Test` annotation.";
return String.format(
"Update usages of TestNG's `@%s` annotation to JUnit 5's `@%s` annotation.", TESTNG_TYPE, JUPITER_TYPE
);
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(Preconditions.or(
new UsesType<>("org.testng.annotations.Test", false),
new FindImports("org.testng.annotations.Test", null).getVisitor()
new UsesType<>(TESTNG_TYPE, false),
new FindImports(TESTNG_TYPE, null).getVisitor()
), new UpdateTestAnnotationToJunit5Visitor());
}

public static final String TESTNG_TYPE = "org.testng.annotations.Test";
public static final String JUPITER_API_NAMESPACE = "org.junit.jupiter.api";
public static final String JUPITER_TYPE = JUPITER_API_NAMESPACE + ".Test";
public static final String JUPITER_ASSERTIONS_TYPE = JUPITER_API_NAMESPACE + ".Assertions";

// inspired by https://github.com/openrewrite/rewrite-testing-frameworks/blob/4e8ba68b2a28a180f84de7bab9eb12b4643e342e/src/main/java/org/openrewrite/java/testing/junit5/UpdateTestAnnotation.java#
private static class UpdateTestAnnotationToJunit5Visitor extends JavaIsoVisitor<ExecutionContext> {

private static final AnnotationMatcher TESTNG_TEST = new AnnotationMatcher("@org.testng.annotations.Test");

private final JavaTemplate displayNameAnnotation = JavaTemplate
.builder("@DisplayName(#{any(java.lang.String)})")
.imports("org.junit.jupiter.api.DisplayName")
.imports(JUPITER_API_NAMESPACE + ".DisplayName")
.javaParser(Parser.jupiter()).build();

private final JavaTemplate disabledAnnotation = JavaTemplate
.builder("@Disabled")
.imports("org.junit.jupiter.api.Disabled")
.imports(JUPITER_API_NAMESPACE + ".Disabled")
.javaParser(Parser.jupiter()).build();

private final JavaTemplate junitExecutable = JavaTemplate
.builder("org.junit.jupiter.api.function.Executable o = () -> #{};")
.builder(JUPITER_API_NAMESPACE + ".function.Executable o = () -> #{};")
.javaParser(Parser.jupiter()).build();

private final JavaTemplate tagAnnotation = JavaTemplate
.builder("@Tag(#{any(java.lang.String)})")
.imports("org.junit.jupiter.api.Tag")
.imports(JUPITER_API_NAMESPACE + ".Tag")
.javaParser(Parser.jupiter()).build();

private final JavaTemplate timeoutAnnotation = JavaTemplate
.builder("@Timeout(value = #{any(long)}, unit = TimeUnit.MILLISECONDS)")
.imports("org.junit.jupiter.api.Timeout", "java.util.concurrent.TimeUnit")
.imports(JUPITER_API_NAMESPACE + ".Timeout", "java.util.concurrent.TimeUnit")
.javaParser(Parser.jupiter()).build();

@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
J.CompilationUnit c = super.visitCompilationUnit(cu, ctx);
if (!c.findType("org.testng.annotations.Test").isEmpty()) {
if (!c.findType(TESTNG_TYPE).isEmpty()) {
// Update other references like `Test.class`.
c = (J.CompilationUnit) new ChangeType("org.testng.annotations.Test", "org.junit.jupiter.api.Test", true)
c = (J.CompilationUnit) new ChangeType(TESTNG_TYPE, JUPITER_TYPE, true)
.getVisitor().visitNonNull(c, ctx);
}

maybeRemoveImport("org.testng.annotations.Test");
maybeRemoveImport(TESTNG_TYPE);
doAfterVisit(new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
@@ -100,15 +107,15 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionCon

@Override
public J.Import visitImport(J.Import anImport, ExecutionContext ctx) {
if ("org.testng.annotations.Test".equals(anImport.getTypeName())) {
if (TESTNG_TYPE.equals(anImport.getTypeName())) {
return Markup.error(anImport, new IllegalStateException("This import should have been removed by this recipe."));
}
return anImport;
}

@Override
public JavaType visitType(@Nullable JavaType javaType, ExecutionContext ctx) {
if (TypeUtils.isOfClassType(javaType, "org.testng.annotations.Test")) {
if (TypeUtils.isOfClassType(javaType, TESTNG_TYPE)) {
getCursor().putMessageOnFirstEnclosing(J.class, "danglingTestRef", true);
}
return javaType;
@@ -117,7 +124,9 @@ public JavaType visitType(@Nullable JavaType javaType, ExecutionContext ctx) {
@Override
public J postVisit(J tree, ExecutionContext ctx) {
if (getCursor().getMessage("danglingTestRef", false)) {
return Markup.warn(tree, new IllegalStateException("This still has a type of `org.testng.annotations.Test`"));
return Markup.warn(tree, new IllegalStateException(
String.format("This still has a type of `%s`", TESTNG_TYPE)
));
}
return tree;
}
@@ -135,7 +144,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
}

if (cta.description != null && !J.Literal.isLiteralValue(cta.description, "")) {
maybeAddImport("org.junit.jupiter.api.DisplayName");
maybeAddImport(JUPITER_API_NAMESPACE + ".DisplayName");
m = displayNameAnnotation.apply(
updateCursor(m),
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName).reversed()),
@@ -144,7 +153,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
}

if (J.Literal.isLiteralValue(cta.enabled, Boolean.FALSE)) {
maybeAddImport("org.junit.jupiter.api.Disabled");
maybeAddImport(JUPITER_API_NAMESPACE + ".Disabled");
m = disabledAnnotation.apply(
updateCursor(m),
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName).reversed())
@@ -162,18 +171,18 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
((J.VariableDeclarations) body.getStatements().get(0))
.getVariables().get(0).getInitializer();

maybeAddImport("org.junit.jupiter.api.Assertions");
maybeAddImport(JUPITER_ASSERTIONS_TYPE);
final List<Object> parameters = Arrays.asList(cta.expectedException, lambda);
final String code = "Assertions.assertThrows(#{any(java.lang.Class)}, #{any(org.junit.jupiter.api.function.Executable)});";
if (!(cta.expectedExceptionMessageRegExp instanceof J.Literal)) {
m = JavaTemplate.builder(code).javaParser(Parser.jupiter())
.imports("org.junit.jupiter.api.Assertions").build()
.imports(JUPITER_ASSERTIONS_TYPE).build()
.apply(updateCursor(m), m.getCoordinates().replaceBody(), parameters.toArray());
} else {
m = JavaTemplate.builder(
"final Throwable thrown = " + code + System.lineSeparator()
+ "Assertions.assertTrue(thrown.getMessage().matches(#{any(java.lang.String)}));"
).javaParser(Parser.jupiter()).imports("org.junit.jupiter.api.Assertions").build()
).javaParser(Parser.jupiter()).imports(JUPITER_ASSERTIONS_TYPE).build()
.apply(
updateCursor(m),
m.getCoordinates().replaceBody(),
@@ -183,7 +192,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex
}

if (cta.groups != null) {
maybeAddImport("org.junit.jupiter.api.Tag");
maybeAddImport(JUPITER_API_NAMESPACE + ".Tag");
if (cta.groups instanceof J.Literal && !J.Literal.isLiteralValue(cta.groups, "")) {
m = tagAnnotation.apply(
updateCursor(m),
@@ -205,7 +214,7 @@ public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, Ex

if (cta.timeout != null) {
maybeAddImport("java.util.concurrent.TimeUnit");
maybeAddImport("org.junit.jupiter.api.Timeout");
maybeAddImport(JUPITER_API_NAMESPACE + ".Timeout");
m = timeoutAnnotation.apply(
updateCursor(m),
m.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)),
@@ -259,13 +268,13 @@ public J.Annotation visitAnnotation(J.Annotation a, ExecutionContext ctx) {
}

if (a.getAnnotationType() instanceof J.FieldAccess) {
return JavaTemplate.builder("@org.junit.jupiter.api.Test")
return JavaTemplate.builder("@" + JUPITER_TYPE)
.javaParser(Parser.jupiter())
.build()
.apply(getCursor(), a.getCoordinates().replace());
} else {
return a.withArguments(null)
.withType(JavaType.ShallowClass.build("org.junit.jupiter.api.Test"));
.withType(JavaType.ShallowClass.build(JUPITER_TYPE));
}
}
}