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 missing @Nested annotation #257

Merged
merged 1 commit into from
Aug 29, 2022
Merged
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
@@ -0,0 +1,121 @@
/*
* 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.junit5;

import lombok.EqualsAndHashCode;
import lombok.Value;
import org.jetbrains.annotations.NotNull;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.search.FindAnnotations;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.TypeUtils;

import java.time.Duration;
import java.util.*;

import static org.openrewrite.Parser.Input.fromString;

@Value
@EqualsAndHashCode(callSuper = true)
public class AddMissingNested extends Recipe {
private static final String NESTED = "org.junit.jupiter.api.Nested";
private static final List<String> TEST_ANNOTATIONS = Arrays.asList(
"org.junit.jupiter.api.Test",
"org.junit.jupiter.api.TestTemplate",
"org.junit.jupiter.api.RepeatedTest",
"org.junit.jupiter.params.ParameterizedTest",
"org.junit.jupiter.api.TestFactory");

@Override
public String getDisplayName() {
return "JUnit5 inner test classes should be annotated with `@Nested`.";
}

@Override
public String getDescription() {
return "Adds `@Nested` to inner classes that contain JUnit 5 tests.";
}

@Override
protected @Nullable TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
return new JavaVisitor<ExecutionContext>() {
@Override
public J visitJavaSourceFile(JavaSourceFile cu, ExecutionContext executionContext) {
TEST_ANNOTATIONS.forEach(ann -> doAfterVisit(new UsesType<>(ann)));
return cu;
}
};
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(1);
}

@Override
public Set<String> getTags() {
return Collections.singleton("RSPEC-5790");
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
cd = cd.withBody((J.Block) new AddNestedAnnotationVisitor().visit(cd.getBody(), ctx, getCursor()));
maybeAddImport(NESTED);
return cd;
}
};
}

public static class AddNestedAnnotationVisitor extends JavaIsoVisitor<ExecutionContext> {
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, ctx);
boolean alreadyNested = classDecl.getLeadingAnnotations().stream()
.anyMatch(a -> TypeUtils.isOfClassType(a.getType(), NESTED));
if (!alreadyNested && hasTestMethods(cd)) {
cd = cd.withTemplate(getNestedJavaTemplate(), cd.getCoordinates().addAnnotation(Comparator.comparing(
J.Annotation::getSimpleName)));
cd.getModifiers().removeIf(modifier -> modifier.getType().equals(J.Modifier.Type.Static));
}
return cd;
}

@NotNull
private JavaTemplate getNestedJavaTemplate() {
return JavaTemplate.builder(this::getCursor, "@Nested")
.javaParser(() -> JavaParser.fromJavaVersion().dependsOn(Collections.singletonList(
fromString("package org.junit.jupiter.api;\npublic @interface Nested {}"))).build())
.imports(NESTED).build();
}

private static boolean hasTestMethods(final J.ClassDeclaration cd) {
return TEST_ANNOTATIONS.stream().anyMatch(ann -> !FindAnnotations.find(cd, "@" + ann).isEmpty());
}
}
}
1 change: 1 addition & 0 deletions src/main/resources/META-INF/rewrite/junit5.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ recipeList:
- org.openrewrite.java.testing.junit5.UpdateMockWebServer
- org.openrewrite.java.testing.junit5.VertxUnitToVertxJunit5
- org.openrewrite.java.testing.junit5.EnclosedToNested
- org.openrewrite.java.testing.junit5.AddMissingNested
- org.openrewrite.java.testing.hamcrest.AddHamcrestIfUsed
- org.openrewrite.maven.RemoveDependency:
groupId: junit
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
* 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.junit5

import org.junit.jupiter.api.Test
import org.openrewrite.java.Assertions.java
import org.openrewrite.java.JavaParser
import org.openrewrite.test.RecipeSpec
import org.openrewrite.test.RewriteTest

class AddMissingNestedTest : RewriteTest {
override fun defaults(spec: RecipeSpec) {
spec.recipe(AddMissingNested())
.parser(JavaParser.fromJavaVersion().classpath("junit").logCompilationWarningsAndErrors(true))
}

@Test
fun `one inner class`() = rewriteRun(java(
"""
import org.junit.jupiter.api.Test;

public class RootTest {
public class InnerTest {
@Test
public void test() {}
}
}
""", """
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class RootTest {
@Nested
public class InnerTest {
@Test
public void test() {}
}
}
"""
))

@Test
fun `multiple inner classes`() = rewriteRun(java(
"""
import org.junit.jupiter.api.Test;

public class RootTest {
public class InnerTest {
@Test
public void test() {}
}

public class Inner2Test {
@Test
public void test() {}

public class InnermostTest {
@Test
public void test() {}
}
}
}
""", """
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class RootTest {
@Nested
public class InnerTest {
@Test
public void test() {}
}

@Nested
public class Inner2Test {
@Test
public void test() {}

@Nested
public class InnermostTest {
@Test
public void test() {}
}
}
}
"""
))

@Test
fun `does not annotate non-test inner class`() = rewriteRun(java(
"""
import org.junit.jupiter.api.Test;

public class RootTest {
public class InnerTest {
@Test
public void test() {}
}

public static class Foo {
public void bar() {}
}
}
""", """
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class RootTest {
@Nested
public class InnerTest {
@Test
public void test() {}
}

public static class Foo {
public void bar() {}
}
}
"""
))

@Test
fun `removes static`() = rewriteRun(java(
"""
import org.junit.jupiter.api.Test;

public class RootTest {
public static class InnerTest {
@Test
public void test() {}
}
}
""", """
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

public class RootTest {
@Nested
public class InnerTest {
@Test
public void test() {}
}
}
"""
))
}