Skip to content

Commit ef96c01

Browse files
amishra-utimtebeekgithub-actions[bot]
authored
Handle non-@rule TemporaryFolder fields (#720)
* Fix handling of annoatated TemporaryFolder fields * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * rebase * Inline `javaParser` method only used once * Update examples.yml * Update usage of annotated trait * Delay looking at rule, and inline JavaTemplates where used --------- Co-authored-by: Tim te Beek <timtebeek@gmail.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Tim te Beek <tim@moderne.io>
1 parent 5e08a00 commit ef96c01

File tree

3 files changed

+170
-27
lines changed

3 files changed

+170
-27
lines changed

src/main/java/org/openrewrite/java/testing/junit5/TemporaryFolderToTempDir.java

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,18 @@
2424
import org.openrewrite.java.*;
2525
import org.openrewrite.java.search.UsesType;
2626
import org.openrewrite.java.tree.*;
27+
import org.openrewrite.marker.Markers;
2728

2829
import java.util.ArrayList;
2930
import java.util.List;
3031
import java.util.Objects;
3132
import java.util.Optional;
3233
import java.util.stream.Collectors;
3334

35+
import static java.util.Collections.emptyList;
36+
import static org.openrewrite.Tree.randomId;
37+
import static org.openrewrite.java.trait.Traits.annotated;
38+
3439
public class TemporaryFolderToTempDir extends Recipe {
3540

3641
@Override
@@ -53,8 +58,12 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
5358

5459
class TemporaryFolderToTempDirVisitor extends JavaVisitor<ExecutionContext> {
5560

56-
final AnnotationMatcher classRule = new AnnotationMatcher("@org.junit.ClassRule");
57-
final AnnotationMatcher rule = new AnnotationMatcher("@org.junit.Rule");
61+
private static final String TEMPORARY_FOLDER = "org.junit.rules.TemporaryFolder";
62+
private static final String TEMP_DIR = "org.junit.jupiter.api.io.TempDir";
63+
private static final AnnotationMatcher CLASS_RULE = new AnnotationMatcher("@org.junit.ClassRule");
64+
private static final AnnotationMatcher RULE = new AnnotationMatcher("@org.junit.Rule");
65+
private static final MethodMatcher NEW_TEMPORARY_FOLDER = new MethodMatcher(TEMPORARY_FOLDER + "<constructor>()");
66+
private static final MethodMatcher NEW_TEMPORARY_FOLDER_WITH_ARG = new MethodMatcher(TEMPORARY_FOLDER + "<constructor>(java.io.File)");
5867

5968
@Override
6069
public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
@@ -64,6 +73,7 @@ public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
6473
"org.junit.rules.TemporaryFolder", "java.io.File", true).getVisitor()
6574
.visit(c, ctx);
6675
maybeAddImport("java.io.File");
76+
maybeAddImport("java.nio.file.Files");
6777
maybeAddImport("org.junit.jupiter.api.io.TempDir");
6878
maybeRemoveImport("org.junit.ClassRule");
6979
maybeRemoveImport("org.junit.Rule");
@@ -75,30 +85,34 @@ public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) {
7585
@Override
7686
public J visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext ctx) {
7787
J.VariableDeclarations mv = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, ctx);
78-
if (!isRuleAnnotatedTemporaryFolder(mv)) {
88+
if (!TypeUtils.isOfClassType(multiVariable.getTypeAsFullyQualified(), TEMPORARY_FOLDER)) {
7989
return mv;
8090
}
81-
String fieldVars = mv.getVariables().stream()
82-
.map(fv -> fv.withInitializer(null))
83-
.map(it -> it.print(getCursor()))
84-
.collect(Collectors.joining(","));
85-
String modifiers = mv.getModifiers().stream().map(it -> it.getType().name().toLowerCase()).collect(Collectors.joining(" "));
86-
return JavaTemplate.builder("@TempDir\n#{} File#{};")
87-
.contextSensitive()
88-
.imports("java.io.File", "org.junit.jupiter.api.io.TempDir")
89-
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "junit-jupiter-api-5"))
90-
.build()
91-
.apply(
92-
updateCursor(mv),
93-
mv.getCoordinates().replace(),
94-
modifiers,
95-
fieldVars
96-
);
91+
mv = mv.withTypeExpression(toFileIdentifier(mv.getTypeExpression()));
92+
return (J.VariableDeclarations) annotated("@org.junit.*Rule")
93+
.asVisitor(a -> JavaTemplate.builder("@TempDir")
94+
.imports(TEMP_DIR)
95+
.javaParser(JavaParser.fromJavaVersion().classpathFromResources(ctx, "junit-jupiter-api-5"))
96+
.build()
97+
.apply(a.getCursor(), a.getTree().getCoordinates().replace()))
98+
.visitNonNull(mv, ctx, getCursor().getParentOrThrow());
9799
}
98100

99-
private boolean isRuleAnnotatedTemporaryFolder(J.VariableDeclarations vd) {
100-
return TypeUtils.isOfClassType(vd.getTypeAsFullyQualified(), "org.junit.rules.TemporaryFolder") &&
101-
vd.getLeadingAnnotations().stream().anyMatch(anno -> classRule.matches(anno) || rule.matches(anno));
101+
@Override
102+
public @Nullable J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
103+
if (NEW_TEMPORARY_FOLDER.matches(newClass)) {
104+
return hasRuleAnnotation() ? null : JavaTemplate.builder("Files.createTempDirectory(\"junit\").toFile()")
105+
.imports("java.nio.file.Files")
106+
.build()
107+
.apply(getCursor(), newClass.getCoordinates().replace());
108+
}
109+
if (NEW_TEMPORARY_FOLDER_WITH_ARG.matches(newClass)) {
110+
return hasRuleAnnotation() ? null : JavaTemplate.builder("Files.createTempDirectory(#{any(java.io.File)}.toPath(), \"junit\").toFile()")
111+
.imports("java.nio.file.Files")
112+
.build()
113+
.apply(getCursor(), newClass.getCoordinates().replace(), newClass.getArguments().get(0));
114+
}
115+
return super.visitNewClass(newClass, ctx);
102116
}
103117

104118
@Override
@@ -125,6 +139,19 @@ private boolean isRuleAnnotatedTemporaryFolder(J.VariableDeclarations vd) {
125139
return mi;
126140
}
127141

142+
private J.Identifier toFileIdentifier(TypeTree typeTree) {
143+
JavaType.ShallowClass fileType = JavaType.ShallowClass.build("java.io.File");
144+
return new J.Identifier(randomId(), typeTree.getPrefix(), Markers.EMPTY, emptyList(), fileType.getClassName(), fileType, null);
145+
}
146+
147+
private boolean hasRuleAnnotation() {
148+
J.VariableDeclarations vd = getCursor().firstEnclosing(J.VariableDeclarations.class);
149+
if (vd == null) {
150+
return false;
151+
}
152+
return vd.getLeadingAnnotations().stream().anyMatch(anno -> CLASS_RULE.matches(anno) || RULE.matches(anno));
153+
}
154+
128155
private J convertToNewFile(J.MethodInvocation mi, ExecutionContext ctx) {
129156
if (mi.getSelect() == null) {
130157
return mi;

src/main/resources/META-INF/rewrite/examples.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,12 +1008,12 @@ examples:
10081008
}
10091009
}
10101010
after: |
1011-
import org.junit.jupiter.api.Assertions;
1011+
import static org.junit.jupiter.api.Assertions.fail;
10121012
10131013
public class Test {
10141014
void test() {
1015-
Assertions.fail("assert false true");
1016-
Assertions.fail("assert true false");
1015+
fail("assert false true");
1016+
fail("assert true false");
10171017
}
10181018
}
10191019
language: java

src/test/java/org/openrewrite/java/testing/junit5/TemporaryFolderToTempDirTest.java

Lines changed: 118 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ public static void init() {
600600
}
601601

602602
@Test
603-
void newTemporaryFolderInstanceAsArgumentNotSupported() {
603+
void newTemporaryFolderInstanceAsArgument() {
604604
//language=java
605605
rewriteRun(
606606
java(
@@ -611,7 +611,19 @@ void why() {
611611
doSomething(new TemporaryFolder());
612612
}
613613
void doSomething(TemporaryFolder tempFolder) {
614+
tempFolder.create();
615+
}
616+
}
617+
""",
618+
"""
619+
import java.io.File;
620+
import java.nio.file.Files;
614621
622+
public class Z {
623+
void why() {
624+
doSomething(Files.createTempDirectory("junit").toFile());
625+
}
626+
void doSomething(File tempFolder) {
615627
}
616628
}
617629
"""
@@ -620,7 +632,7 @@ void doSomething(TemporaryFolder tempFolder) {
620632
}
621633

622634
@Test
623-
void notSupported() {
635+
void temporaryFolderInstanceAsParameter() {
624636
//language=java
625637
rewriteRun(
626638
java(
@@ -629,12 +641,27 @@ void notSupported() {
629641
public class Z {
630642
void why() {
631643
TemporaryFolder t = new TemporaryFolder();
644+
t.create();
632645
doSomething(t);
633646
}
634647
void doSomething(TemporaryFolder tempFolder) {
635648
636649
}
637650
}
651+
""",
652+
"""
653+
import java.io.File;
654+
import java.nio.file.Files;
655+
656+
public class Z {
657+
void why() {
658+
File t = Files.createTempDirectory("junit").toFile();
659+
doSomething(t);
660+
}
661+
void doSomething(File tempFolder) {
662+
663+
}
664+
}
638665
"""
639666
)
640667
);
@@ -695,4 +722,93 @@ private static File newFolder(File root, String... subDirs) throws IOException {
695722
)
696723
);
697724
}
725+
726+
@Test
727+
void notAsRule() {
728+
//language=java
729+
rewriteRun(
730+
java(
731+
"""
732+
import java.io.File;
733+
import java.io.IOException;
734+
import org.junit.rules.TemporaryFolder;
735+
import org.junit.Test;
736+
737+
public class TempDirTest {
738+
@Test
739+
void testPath() throws IOException {
740+
TemporaryFolder t = new TemporaryFolder();
741+
File f = t.newFile("foo.txt");
742+
}
743+
}
744+
""",
745+
"""
746+
import java.io.File;
747+
import java.io.IOException;
748+
import java.nio.file.Files;
749+
750+
import org.junit.Test;
751+
752+
public class TempDirTest {
753+
@Test
754+
void testPath() throws IOException {
755+
File t = Files.createTempDirectory("junit").toFile();
756+
File f = newFile(t, "foo.txt");
757+
}
758+
759+
private static File newFile(File parent, String child) throws IOException {
760+
File result = new File(parent, child);
761+
result.createNewFile();
762+
return result;
763+
}
764+
}
765+
"""
766+
)
767+
);
768+
}
769+
770+
@Test
771+
void temporaryFolderWithParenDir() {
772+
//language=java
773+
rewriteRun(
774+
java(
775+
"""
776+
import java.io.File;
777+
import java.io.IOException;
778+
import org.junit.rules.TemporaryFolder;
779+
import org.junit.Test;
780+
781+
public class TempDirTest {
782+
@Test
783+
void testPath() throws IOException {
784+
TemporaryFolder t = new TemporaryFolder(new File("parent"));
785+
t.create();
786+
File f = t.newFile("foo.txt");
787+
}
788+
}
789+
""",
790+
"""
791+
import java.io.File;
792+
import java.io.IOException;
793+
import java.nio.file.Files;
794+
795+
import org.junit.Test;
796+
797+
public class TempDirTest {
798+
@Test
799+
void testPath() throws IOException {
800+
File t = Files.createTempDirectory(new File("parent").toPath(), "junit").toFile();
801+
File f = newFile(t, "foo.txt");
802+
}
803+
804+
private static File newFile(File parent, String child) throws IOException {
805+
File result = new File(parent, child);
806+
result.createNewFile();
807+
return result;
808+
}
809+
}
810+
"""
811+
)
812+
);
813+
}
698814
}

0 commit comments

Comments
 (0)