diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java index 39b1a5a06d..578dc7aa4f 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class BumpThisNumberIfACustomStepChangesTest extends GradleIntegrationTest { private void writeBuildFile(String toInsert) throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -39,14 +38,13 @@ private void writeBuildFile(String toInsert) throws IOException { } private void writeContentWithBadFormatting() throws IOException { - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); } @Override protected void applyIsUpToDate(boolean upToDate) throws IOException { super.applyIsUpToDate(upToDate); - String result = read("README.md"); - Assert.assertEquals("abc", result); + assertFile("README.md").hasContent("abc"); } @Test diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CustomLazyGroovyTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CustomLazyGroovyTest.java index ddcab44f49..3198aaf9c1 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CustomLazyGroovyTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/CustomLazyGroovyTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class CustomLazyGroovyTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -35,9 +34,8 @@ public void integration() throws IOException { " }", " }", "}"); - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("README.md"); - Assert.assertEquals("abc", result); + assertFile("README.md").hasContent("abc"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java index 1c47c0621c..0a5f5e5f75 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/DiffMessageFormatterTest.java @@ -73,7 +73,7 @@ protected String getTaskErrorMessage(SpotlessTask task) { @Test public void lineEndingProblem() throws Exception { - SpotlessTask task = create(createTestFile("testFile", "A\r\nB\r\nC\r\n")); + SpotlessTask task = create(setFile("testFile").toContent("A\r\nB\r\nC\r\n")); assertTaskFailure(task, " testFile", " @@ -1,3 +1,3 @@", @@ -87,7 +87,7 @@ public void lineEndingProblem() throws Exception { @Test public void whitespaceProblem() throws Exception { - SpotlessTask task = create(createTestFile("testFile", "A \nB\t\nC \n")); + SpotlessTask task = create(setFile("testFile").toContent("A \nB\t\nC \n")); task.addStep(FormatterStep.createNeverUpToDate("trimTrailing", input -> { Pattern pattern = Pattern.compile("[ \t]+$", Pattern.UNIX_LINES | Pattern.MULTILINE); return pattern.matcher(input).replaceAll(""); @@ -106,8 +106,8 @@ public void whitespaceProblem() throws Exception { @Test public void multipleFiles() throws Exception { SpotlessTask task = create( - createTestFile("A", "1\r\n2\r\n"), - createTestFile("B", "3\n4\r\n")); + setFile("A").toContent("1\r\n2\r\n"), + setFile("B").toContent("3\n4\r\n")); assertTaskFailure(task, " A", " @@ -1,2 +1,2 @@", @@ -126,7 +126,7 @@ public void multipleFiles() throws Exception { public void manyFiles() throws Exception { List testFiles = new ArrayList<>(); for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST - 1; ++i) { - testFiles.add(createTestFile(Integer.toString(i) + ".txt", "1\r\n2\r\n")); + testFiles.add(setFile(Integer.toString(i) + ".txt").toContent("1\r\n2\r\n")); } SpotlessTask task = create(testFiles); assertTaskFailure(task, @@ -199,7 +199,7 @@ public void manyFiles() throws Exception { public void manyManyFiles() throws Exception { List testFiles = new ArrayList<>(); for (int i = 0; i < 9 + DiffMessageFormatter.MAX_FILES_TO_LIST; ++i) { - testFiles.add(createTestFile(Integer.toString(i) + ".txt", "1\r\n2\r\n")); + testFiles.add(setFile(Integer.toString(i) + ".txt").toContent("1\r\n2\r\n")); } SpotlessTask task = create(testFiles); assertTaskFailure(task, @@ -266,7 +266,7 @@ public void longFile() throws Exception { builder.append(i); builder.append("\r\n"); } - SpotlessTask task = create(createTestFile("testFile", builder.toString())); + SpotlessTask task = create(setFile("testFile").toContent(builder.toString())); assertTaskFailure(task, " testFile", " @@ -1,1000 +1,1000 @@", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/EncodingTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/EncodingTest.java index ee6df28abe..a7a2334e5d 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/EncodingTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/EncodingTest.java @@ -17,15 +17,12 @@ import java.nio.charset.Charset; -import org.junit.Assert; import org.junit.Test; -import com.diffplug.spotless.LineEnding; - public class EncodingTest extends GradleIntegrationTest { @Test public void defaultIsUtf8() throws Exception { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -35,14 +32,14 @@ public void defaultIsUtf8() throws Exception { " custom 'replaceMicro', { it.replace('µ', 'A') }", " }", "}"); - write("test.java", "µ"); + setFile("test.java").toContent("µ"); gradleRunner().withArguments("spotlessApply").build(); - Assert.assertEquals("A", read("test.java")); + assertFile("test.java").hasContent("A"); } @Test public void globalIsRespected() throws Exception { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -53,14 +50,14 @@ public void globalIsRespected() throws Exception { " }", " encoding 'US-ASCII'", "}"); - write("test.java", "µ"); + setFile("test.java").toContent("µ"); gradleRunner().withArguments("spotlessApply").build(); - Assert.assertEquals("??", read("test.java")); + assertFile("test.java").hasContent("??"); } @Test public void globalIsRespectedButCanBeOverridden() throws Exception { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -76,12 +73,10 @@ public void globalIsRespectedButCanBeOverridden() throws Exception { " }", " encoding 'US-ASCII'", "}"); - write("test.java", "µ"); - write("utf32.encoded", LineEnding.UNIX, Charset.forName("UTF-32"), "µ"); - Assert.assertEquals("µ", read("utf32.encoded", Charset.forName("UTF-32"))); - + setFile("test.java").toContent("µ"); + setFile("utf32.encoded").toContent("µ", Charset.forName("UTF-32")); gradleRunner().withArguments("spotlessApply").build(); - Assert.assertEquals("??", read("test.java")); - Assert.assertEquals("A", read("utf32.encoded", Charset.forName("UTF-32"))); + assertFile("test.java").hasContent("??"); + assertFile("utf32.encoded").hasContent("A", Charset.forName("UTF-32")); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrow.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrow.java index a9c718f7c3..645ad5d32c 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrow.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrow.java @@ -49,7 +49,7 @@ private void writeBuild(String... toInsert) throws IOException { lines.add(" }"); lines.add(" }"); lines.addAll(Arrays.asList(toInsert)); - write("build.gradle", lines.toArray(new String[lines.size()])); + setFile("build.gradle").toContent(lines.stream().collect(Collectors.joining("\n"))); } @Test @@ -57,7 +57,7 @@ public void passesIfNoException() throws Exception { writeBuild( " } // format", "} // spotless"); - write("README.md", "This code is fun."); + setFile("README.md").toContent("This code is fun."); runWithSuccess(":spotlessMisc"); } @@ -66,7 +66,7 @@ public void anyExceptionShouldFail() throws Exception { writeBuild( " } // format", "} // spotless"); - write("README.md", "This code is fubar."); + setFile("README.md").toContent("This code is fubar."); runWithFailure( ":spotlessMiscStep 'no swearing' found problem in 'README.md':", "No swearing!", @@ -79,7 +79,7 @@ public void unlessEnforceCheckIsFalse() throws Exception { " } // format", " enforceCheck false", "} // spotless"); - write("README.md", "This code is fubar."); + setFile("README.md").toContent("This code is fubar."); runWithSuccess(":compileJava UP-TO-DATE"); } @@ -89,7 +89,7 @@ public void unlessExemptedByStep() throws Exception { " ignoreErrorForStep 'no swearing'", " } // format", "} // spotless"); - write("README.md", "This code is fubar."); + setFile("README.md").toContent("This code is fubar."); runWithSuccess(":spotlessMisc", "Unable to apply step 'no swearing' to 'README.md'"); } @@ -100,7 +100,7 @@ public void unlessExemptedByPath() throws Exception { " ignoreErrorForPath 'README.md'", " } // format", "} // spotless"); - write("README.md", "This code is fubar."); + setFile("README.md").toContent("This code is fubar."); runWithSuccess(":spotlessMisc", "Unable to apply step 'no swearing' to 'README.md'"); } @@ -112,7 +112,7 @@ public void failsIfNeitherStepNorFileExempted() throws Exception { " ignoreErrorForPath 'nope'", " } // format", "} // spotless"); - write("README.md", "This code is fubar."); + setFile("README.md").toContent("This code is fubar."); runWithFailure( ":spotlessMiscStep 'no swearing' found problem in 'README.md':", "No swearing!", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java index 4d7e01a3b1..a0220e9013 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FileTreeTest.java @@ -43,7 +43,7 @@ public void fileTree() throws IOException { @Test public void absolutePathDoesntWork() throws IOException { - File someFile = write("someFolder/someFile"); + File someFile = setFile("someFolder/someFile").toContent(""); File someFolder = someFile.getParentFile(); fileTree.exclude(someFolder.getAbsolutePath()); Assertions.assertThat(fileTree).containsExactlyInAnyOrder(someFile); @@ -51,7 +51,7 @@ public void absolutePathDoesntWork() throws IOException { @Test public void relativePathDoes() throws IOException { - File someFile = write("someFolder/someFile"); + File someFile = setFile("someFolder/someFile").toContent(""); File someFolder = someFile.getParentFile(); fileTree.exclude(relativize(rootFolder(), someFolder)); Assertions.assertThat(fileTree).containsExactlyInAnyOrder(); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java index 2ff7a6a51c..af17fbb09c 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FormatTaskTest.java @@ -46,31 +46,31 @@ public void createTask() { @Test(expected = GradleException.class) public void testLineEndingsCheckFail() throws IOException { checkTask.setLineEndingsPolicy(LineEnding.UNIX.createPolicy()); - checkTask.setTarget(Collections.singleton(createTestFile("testFile", "\r\n"))); + checkTask.setTarget(Collections.singleton(setFile("testFile").toContent("\r\n"))); checkTask.execute(); } @Test public void testLineEndingsCheckPass() throws IOException { checkTask.setLineEndingsPolicy(LineEnding.UNIX.createPolicy()); - checkTask.setTarget(Collections.singleton(createTestFile("testFile", "\n"))); + checkTask.setTarget(Collections.singleton(setFile("testFile").toContent("\n"))); checkTask.execute(); } @Test public void testLineEndingsApply() throws IOException { - File testFile = createTestFile("testFile", "\r\n"); + File testFile = setFile("testFile").toContent("\r\n"); applyTask.setLineEndingsPolicy(LineEnding.UNIX.createPolicy()); applyTask.setTarget(Collections.singleton(testFile)); applyTask.execute(); - assertFileContent("\n", testFile); + assertFile(testFile).hasContent("\n"); } @Test public void testStepCheckFail() throws IOException { - File testFile = createTestFile("testFile", "apple"); + File testFile = setFile("testFile").toContent("apple"); checkTask.setTarget(Collections.singleton(testFile)); checkTask.addStep(FormatterStep.createNeverUpToDate("double-p", content -> content.replace("pp", "p"))); @@ -81,28 +81,28 @@ public void testStepCheckFail() throws IOException { " +aple"); Assertions.assertThatThrownBy(() -> checkTask.execute()).hasStackTraceContaining(diff); - assertFileContent("apple", testFile); + assertFile(testFile).hasContent("apple"); } @Test public void testStepCheckPass() throws IOException { - File testFile = createTestFile("testFile", "aple"); + File testFile = setFile("testFile").toContent("aple"); checkTask.setTarget(Collections.singleton(testFile)); checkTask.addStep(FormatterStep.createNeverUpToDate("double-p", content -> content.replace("pp", "p"))); checkTask.execute(); - assertFileContent("aple", testFile); + assertFile(testFile).hasContent("aple"); } @Test public void testStepApply() throws IOException { - File testFile = createTestFile("testFile", "apple"); + File testFile = setFile("testFile").toContent("apple"); applyTask.setTarget(Collections.singleton(testFile)); applyTask.addStep(FormatterStep.createNeverUpToDate("double-p", content -> content.replace("pp", "p"))); applyTask.execute(); - assertFileContent("aple", testFile); + assertFile(testFile).hasContent("aple"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java index 5f08fd1200..a8c858c4b2 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/FreshMarkExtensionTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class FreshMarkExtensionTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "buildscript { repositories { mavenCentral() } }", "plugins {", " id 'java'", @@ -37,11 +36,8 @@ public void integration() throws IOException { " }", " }", "}"); - String unformatted = getTestResource("freshmark/FreshMarkUnformatted.test"); - write("README.md", unformatted); + setFile("README.md").toResource("freshmark/FreshMarkUnformatted.test"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("README.md"); - String formatted = getTestResource("freshmark/FreshMarkFormatted.test"); - Assert.assertEquals(formatted, result); + assertFile("README.md").sameAsResource("freshmark/FreshMarkFormatted.test"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GoogleJavaFormatIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GoogleJavaFormatIntegrationTest.java index e1c67217cb..cbd9e837de 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GoogleJavaFormatIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GoogleJavaFormatIntegrationTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class GoogleJavaFormatIntegrationTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "buildscript { repositories { mavenCentral() } }", "plugins {", " id 'com.diffplug.gradle.spotless'", @@ -35,16 +34,12 @@ public void integration() throws IOException { " googleJavaFormat('1.2')", " }", "}"); - String input = getTestResource("java/googlejavaformat/JavaCodeUnformatted.test"); - write("test.java", input); - gradleRunner().withArguments("spotlessApply").build(); - String result = read("test.java"); - String output = getTestResource("java/googlejavaformat/JavaCodeFormatted.test"); - Assert.assertEquals(output, result); + setFile("test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); + gradleRunner().withArguments("spotlessApply").build(); + assertFile("test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); checkRunsThenUpToDate(); - replace("build.gradle", "googleJavaFormat('1.2')", "googleJavaFormat('1.3')"); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java index fc45e92876..06c2314019 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIncrementalResolutionTest.java @@ -31,7 +31,7 @@ public class GradleIncrementalResolutionTest extends GradleIntegrationTest { @Test public void failureDoesntTriggerAll() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -86,7 +86,7 @@ private void writeState(String state) throws IOException { boolean exists = new File(rootFolder(), filename(letter)).exists(); boolean needsChanging = exists && !read(filename(letter)).trim().equals(letter); if (!exists || needsChanging) { - write(filename(letter), letter); + setFile(filename(letter)).toContent(letter); } } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationTest.java index aad54bc045..9f9a2618e6 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationTest.java @@ -53,7 +53,7 @@ public class GradleIntegrationTest extends ResourceHarness { */ @Before public void gitAttributes() throws IOException { - write(".gitattributes", "* text eol=lf"); + setFile(".gitattributes").toContent("* text eol=lf"); } protected final GradleRunner gradleRunner() throws IOException { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java index 531b7cb4e4..aaa3d7cd58 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyExtensionTest.java @@ -15,7 +15,6 @@ */ package com.diffplug.gradle.spotless; -import java.io.File; import java.io.IOException; import org.assertj.core.api.Assertions; @@ -24,7 +23,7 @@ public class GroovyExtensionTest extends GradleIntegrationTest { - private final String HEADER = "//My tests header"; + private static final String HEADER = "//My tests header"; @Test public void includeJava() throws IOException { @@ -38,7 +37,7 @@ public void excludeJava() throws IOException { private void testIncludeExcludeOption(boolean excludeJava) throws IOException { String excludeStatement = excludeJava ? "excludeJava()" : ""; - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -51,33 +50,26 @@ private void testIncludeExcludeOption(boolean excludeJava) throws IOException { " }", "}"); - String original = getTestResource("groovy/licenseheader/JavaCodeWithoutHeader.test"); + String withoutHeader = getTestResource("groovy/licenseheader/JavaCodeWithoutHeader.test"); - File javaSrcJavaFile = write("src/main/java/test.java", original); - File groovySrcJavaFile = write("src/main/groovy/test.java", original); - File groovySrcGroovyFile = write("src/main/groovy/test.groovy", original); + setFile("src/main/java/test.java").toContent(withoutHeader); + setFile("src/main/groovy/test.java").toContent(withoutHeader); + setFile("src/main/groovy/test.groovy").toContent(withoutHeader); - // write appends a line ending so re-read to see what the original currently looks like - original = read("src/main/java/test.java"); - - // Run gradleRunner().withArguments("spotlessApply").build(); - // Common checks - assertFileContent(original, javaSrcJavaFile); - - Assertions.assertThat(read(groovySrcGroovyFile.toPath())).contains(HEADER); - + assertFile("src/main/java/test.java").hasContent(withoutHeader); + assertFile("src/main/groovy/test.groovy").hasContent(HEADER + "\n" + withoutHeader); if (excludeJava) { - assertFileContent(original, groovySrcJavaFile); + assertFile("src/main/groovy/test.java").hasContent(withoutHeader); } else { - Assertions.assertThat(read(groovySrcJavaFile.toPath())).contains(HEADER); + assertFile("src/main/groovy/test.java").hasContent(HEADER + "\n" + withoutHeader); } } @Test public void excludeJavaWithCustomTarget() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -100,7 +92,7 @@ public void excludeJavaWithCustomTarget() throws IOException { @Test public void groovyPluginMissingCheck() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java index f3059e225c..fc4de71b15 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GroovyGradleExtensionTest.java @@ -15,15 +15,14 @@ */ package com.diffplug.gradle.spotless; -import java.io.File; import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.Test; -public class GroovyGradleExtensionTest extends GradleIntegrationTest { +import com.diffplug.common.base.StringPrinter; - private final String HEADER = "//My tests header"; +public class GroovyGradleExtensionTest extends GradleIntegrationTest { + private static final String HEADER = "//My tests header"; @Test public void defaultTarget() throws IOException { @@ -37,7 +36,7 @@ public void customTarget() throws IOException { private void testTarget(boolean useDefaultTarget) throws IOException { String target = useDefaultTarget ? "" : "target 'other.gradle'"; - File projectFile = write("build.gradle", + String buildContent = StringPrinter.buildStringFromLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -47,18 +46,14 @@ private void testTarget(boolean useDefaultTarget) throws IOException { " licenseHeader('" + HEADER + "', 'plugins')", " }", "}"); + setFile("build.gradle").toContent(buildContent); - // write appends a line ending so re-read to see what the original currently looks like - String unModified = read(projectFile.toPath()); - - // Run gradleRunner().withArguments("spotlessApply").build(); if (useDefaultTarget) { - Assertions.assertThat(read(projectFile.toPath())).contains(HEADER); + assertFile("build.gradle").hasContent(HEADER + "\n" + buildContent); } else { - assertFileContent(unModified, projectFile); + assertFile("build.gradle").hasContent(buildContent); } } - } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java index 41829f8095..eb896a7214 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/JavaDefaultTargetTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class JavaDefaultTargetTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "buildscript { repositories { mavenCentral() } }", "plugins {", " id 'com.diffplug.gradle.spotless'", @@ -36,24 +35,14 @@ public void integration() throws IOException { " googleJavaFormat('1.2')", " }", "}"); - String input = getTestResource("java/googlejavaformat/JavaCodeUnformatted.test"); - write("src/main/java/test.java", input); - write("src/main/groovy/test.java", input); - write("src/main/groovy/test.groovy", input); - - // write appends a line ending so re-read to see what groovy currently looks like - String groovyInput = read("src/main/groovy/test.groovy"); + setFile("src/main/java/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); + setFile("src/main/groovy/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); + setFile("src/main/groovy/test.groovy").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("src/main/java/test.java"); - String output = getTestResource("java/googlejavaformat/JavaCodeFormatted.test"); - Assert.assertEquals("Java code in the java directory should be formatted.", output, result); - - result = read("src/main/groovy/test.java"); - Assert.assertEquals("Java code in the groovy directory should be formatted.", output, result); - - result = read("src/main/groovy/test.groovy"); - Assert.assertEquals("Groovy code in the groovy directory should not be formatted.", groovyInput, result); + assertFile("src/main/java/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + assertFile("src/main/groovy/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + assertFile("src/main/groovy/test.groovy").sameAsResource("java/googlejavaformat/JavaCodeUnformatted.test"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinExtensionTest.java index e8a1cc5add..4bc6df1993 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinExtensionTest.java @@ -15,12 +15,9 @@ */ package com.diffplug.gradle.spotless; -import java.io.File; import java.io.IOException; import java.time.YearMonth; -import org.assertj.core.api.Assertions; -import org.junit.Assert; import org.junit.Test; public class KotlinExtensionTest extends GradleIntegrationTest { @@ -29,7 +26,7 @@ public class KotlinExtensionTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -40,16 +37,14 @@ public void integration() throws IOException { " ktlint()", " }", "}"); - write("src/main/kotlin/basic.kt", getTestResource("kotlin/ktlint/basic.dirty")); + setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktlint/basic.dirty"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("src/main/kotlin/basic.kt"); - String formatted = getTestResource("kotlin/ktlint/basic.clean"); - Assert.assertEquals(formatted, result); + assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktlint/basic.clean"); } @Test public void testWithHeader() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -61,23 +56,14 @@ public void testWithHeader() throws IOException { " ktlint()", " }", "}"); - final File testFile = write("src/main/kotlin/test.kt", getTestResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test")); - final String original = read(testFile.toPath()); + setFile("src/main/kotlin/test.kt").toResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test"); gradleRunner().withArguments("spotlessApply").build(); - final String result = read(testFile.toPath()); - Assertions - .assertThat(result) - // Make sure the header gets added. - .startsWith(HEADER) - // Make sure that the rest of the file is still there with nothing removed. - .endsWith(original) - // Make sure that no additional stuff got added to the file. - .contains(HEADER + '\n' + original); + assertFile("src/main/kotlin/test.kt").hasContent(HEADER + "\n" + getTestResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test")); } @Test public void testWithCustomHeaderSeparator() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -89,23 +75,14 @@ public void testWithCustomHeaderSeparator() throws IOException { " ktlint()", " }", "}"); - final File testFile = write("src/main/kotlin/test.kt", getTestResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test")); - final String original = read(testFile.toPath()); + setFile("src/main/kotlin/test.kt").toResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test"); gradleRunner().withArguments("spotlessApply").build(); - final String result = read(testFile.toPath()); - Assertions - .assertThat(result) - // Make sure the header gets added. - .startsWith(HEADER) - // Make sure that the rest of the file is still there with nothing removed. - .endsWith(original) - // Make sure that no additional stuff got added to the file. - .contains(HEADER + '\n' + original); + assertFile("src/main/kotlin/test.kt").hasContent(HEADER + "\n" + getTestResource("kotlin/licenseheader/KotlinCodeWithoutHeader.test")); } @Test public void testWithNonStandardYearSeparator() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -118,22 +95,14 @@ public void testWithNonStandardYearSeparator() throws IOException { " }", "}"); - final File testFile = write("src/main/kotlin/test.kt", getTestResource("kotlin/licenseheader/KotlinCodeWithMultiYearHeader.test")); - final String original = read(testFile.toPath()); - final File testFile2 = write("src/main/kotlin/test2.kt", getTestResource("kotlin/licenseheader/KotlinCodeWithMultiYearHeader2.test")); - final String original2 = read(testFile.toPath()); + setFile("src/main/kotlin/test.kt").toResource("kotlin/licenseheader/KotlinCodeWithMultiYearHeader.test"); + setFile("src/main/kotlin/test2.kt").toResource("kotlin/licenseheader/KotlinCodeWithMultiYearHeader2.test"); gradleRunner().withArguments("spotlessApply").build(); - final String result = read(testFile.toPath()); - final String result2 = read(testFile2.toPath()); - - Assertions - .assertThat(result) - // Make sure the a "valid" header isn't changed - .contains("// License Header 2012, 2014"); - - Assertions - .assertThat(result2) - // Make sure that an "invalid" header is rewritten - .startsWith(HEADER_WITH_YEAR.replace("$YEAR", String.valueOf(YearMonth.now().getYear()))); + assertFile("src/main/kotlin/test.kt").matches(matcher -> { + matcher.startsWith("// License Header 2012, 2014"); + }); + assertFile("src/main/kotlin/test2.kt").matches(matcher -> { + matcher.startsWith(HEADER_WITH_YEAR.replace("$YEAR", String.valueOf(YearMonth.now().getYear()))); + }); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java index 36f9ae5f7f..f154d738a0 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/KotlinGradleExtensionTest.java @@ -17,7 +17,6 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class KotlinGradleExtensionTest extends GradleIntegrationTest { @@ -32,7 +31,7 @@ public void integration_script_in_subdir() throws IOException { } private void testInDirectory(final String directory) throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -48,17 +47,14 @@ private void testInDirectory(final String directory) throws IOException { if (directory != null) { filePath = directory + "/" + filePath; } - write(filePath, - getTestResource("kotlin/ktlint/basic.dirty")); + setFile(filePath).toResource("kotlin/ktlint/basic.dirty"); gradleRunner().withArguments("spotlessApply").build(); - String result = read(filePath); - String formatted = getTestResource("kotlin/ktlint/basic.clean"); - Assert.assertEquals(formatted, result); + assertFile(filePath).sameAsResource("kotlin/ktlint/basic.clean"); } @Test public void integration_default() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -69,17 +65,14 @@ public void integration_default() throws IOException { " ktlint()", " }", "}"); - write("configuration.gradle.kts", - getTestResource("kotlin/ktlint/basic.dirty")); + setFile("configuration.gradle.kts").toResource("kotlin/ktlint/basic.dirty"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("configuration.gradle.kts"); - String formatted = getTestResource("kotlin/ktlint/basic.clean"); - Assert.assertEquals(formatted, result); + assertFile("configuration.gradle.kts").sameAsResource("kotlin/ktlint/basic.clean"); } @Test public void integration_lint_script_files_without_top_level_declaration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'nebula.kotlin' version '1.0.6'", " id 'com.diffplug.gradle.spotless'", @@ -90,10 +83,8 @@ public void integration_lint_script_files_without_top_level_declaration() throws " ktlint()", " }", "}"); - write("configuration.gradle.kts", "buildscript {}"); + setFile("configuration.gradle.kts").toContent("buildscript {}"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("configuration.gradle.kts"); - String formatted = "buildscript {}"; - Assert.assertEquals(formatted, result); + assertFile("configuration.gradle.kts").hasContent("buildscript {}"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java index 47b96c19fc..8292bc3d34 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/PaddedCellTaskTest.java @@ -51,7 +51,7 @@ private class Bundle { SpotlessTask apply; Bundle(String name, FormatterFunc function) throws IOException { - file = createTestFile("src/test." + name, "CCC"); + file = setFile("src/test." + name).toContent("CCC"); FormatterStep step = FormatterStep.createNeverUpToDate(name, function); check = createCheckTask(name, step); apply = createApplyTask(name, step); @@ -121,9 +121,9 @@ public void paddedCellApply() throws IOException { converge.apply.execute(); diverge.apply.execute(); - assertFileContent("A", cycle.file); // cycle -> first element in cycle - assertFileContent("", converge.file); // converge -> converges - assertFileContent("CCC", diverge.file); // diverge -> no change + assertFile(cycle.file).hasContent("A"); // cycle -> first element in cycle + assertFile(converge.file).hasContent(""); // converge -> converges + assertFile(diverge.file).hasContent("CCC"); // diverge -> no change cycle.check.execute(); converge.check.execute(); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ScalaExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ScalaExtensionTest.java index ee0d033001..d367e5fdc4 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ScalaExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ScalaExtensionTest.java @@ -17,13 +17,12 @@ import java.io.IOException; -import org.junit.Assert; import org.junit.Test; public class ScalaExtensionTest extends GradleIntegrationTest { @Test public void integration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "buildscript { repositories { mavenCentral() } }", "plugins {", " id 'com.diffplug.gradle.spotless'", @@ -34,11 +33,9 @@ public void integration() throws IOException { " scalafmt().configFile('scalafmt.conf')", " }", "}"); - write("src/main/scala/basic.scala", getTestResource("scala/scalafmt/basic.dirty")); - write("scalafmt.conf", getTestResource("scala/scalafmt/scalafmt.conf")); + setFile("scalafmt.conf").toResource("scala/scalafmt/scalafmt.conf"); + setFile("src/main/scala/basic.scala").toResource("scala/scalafmt/basic.dirty"); gradleRunner().withArguments("spotlessApply").build(); - String result = read("src/main/scala/basic.scala"); - String formatted = getTestResource("scala/scalafmt/basic.cleanWithCustomConf"); - Assert.assertEquals(formatted, result); + assertFile("src/main/scala/basic.scala").sameAsResource("scala/scalafmt/basic.cleanWithCustomConf"); } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SqlExtensionTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SqlExtensionTest.java index 0d6748de11..77aed402ae 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SqlExtensionTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SqlExtensionTest.java @@ -15,7 +15,6 @@ */ package com.diffplug.gradle.spotless; -import java.io.File; import java.io.IOException; import org.junit.Test; @@ -24,7 +23,7 @@ public class SqlExtensionTest extends GradleIntegrationTest { @Test public void should_format_sql_with_default_configuration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -34,18 +33,14 @@ public void should_format_sql_with_default_configuration() throws IOException { " }", "}"); - File sqlFile = write("src/main/resources/aFolder/create.sql", getTestResource("sql/dbeaver/create.dirty")); - - // Run + setFile("src/main/resources/aFolder/create.sql").toResource("sql/dbeaver/create.dirty"); gradleRunner().withArguments("spotlessApply").build(); - - // Common checks - assertFileContent(getTestResource("sql/dbeaver/create.clean"), sqlFile); + assertFile("src/main/resources/aFolder/create.sql").sameAsResource("sql/dbeaver/create.clean"); } @Test public void should_format_sql_with_alternative_configuration() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -54,15 +49,10 @@ public void should_format_sql_with_alternative_configuration() throws IOExceptio " dbeaver().configFile 'myConfig.properties'", " }", "}"); + setFile("myConfig.properties").toResource("sql/dbeaver/sqlConfig2.properties"); - File sqlFile = write("src/main/resources/aFolder/create.sql", getTestResource("sql/dbeaver/create.dirty")); - write("myConfig.properties", getTestResource("sql/dbeaver/sqlConfig2.properties")); - - // Run + setFile("src/main/resources/aFolder/create.sql").toResource("sql/dbeaver/create.dirty"); gradleRunner().withArguments("spotlessApply").build(); - - // Common checks - assertFileContent(getTestResource("sql/dbeaver/create.clean.alternative"), sqlFile); + assertFile("src/main/resources/aFolder/create.sql").sameAsResource("sql/dbeaver/create.clean.alternative"); } - } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java index aa12d7e406..5033c1bf13 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java @@ -22,7 +22,7 @@ public class UpToDateTest extends GradleIntegrationTest { /** Requires that README be lowercase. */ private void writeBuildFile() throws IOException { - write("build.gradle", + setFile("build.gradle").toLines( "plugins {", " id 'com.diffplug.gradle.spotless'", "}", @@ -40,7 +40,7 @@ private void writeBuildFile() throws IOException { @Test public void testNormalCase() throws IOException { writeBuildFile(); - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); // first time, the task runs as expected applyIsUpToDate(false); assertFile("README.md").hasContent("abc"); @@ -58,13 +58,13 @@ public void testNormalCase() throws IOException { @Test public void testNearPathologicalCase() throws IOException { writeBuildFile(); - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); // first time, up-to-date is false applyIsUpToDate(false); assertFile("README.md").hasContent("abc"); // now we'll change the file - write("README.md", "AB"); + setFile("README.md").toContent("AB"); // as expected, the task will run again applyIsUpToDate(false); assertFile("README.md").hasContent("ab"); @@ -76,13 +76,13 @@ public void testNearPathologicalCase() throws IOException { @Test public void testPathologicalCase() throws IOException { writeBuildFile(); - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); // first time, up-to-date is false applyIsUpToDate(false); assertFile("README.md").hasContent("abc"); // now we'll change the file back to EXACTLY its original content - write("README.md", "ABC"); + setFile("README.md").toContent("ABC"); // the task should run again, but instead the next line will // fail an assertion, because the task is actually reported as up-to-date applyIsUpToDate(false); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java index fdc9916f9c..f60d0654d6 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/IncludesExcludesTest.java @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.maven; -import static org.assertj.core.api.Assertions.assertThat; - import java.io.IOException; import org.junit.Test; @@ -43,7 +41,7 @@ public void testDefaultIncludesJava() throws Exception { " ${basedir}/formatter.xml", ""); - write("formatter.xml", getTestResource("java/eclipse/formatter.xml")); + setFile("formatter.xml").toResource("java/eclipse/formatter.xml"); writeUnformattedJava(unformattedCorrectLocation1); writeUnformattedJava(unformattedCorrectLocation2); @@ -155,34 +153,34 @@ public void testExclude() throws Exception { } private void writeFormattedJava(String target) throws IOException { - write(target, getTestResource(JAVA_FORMATTED)); + setFile(target).toResource(JAVA_FORMATTED); } private void writeUnformattedJava(String target) throws IOException { - write(target, getTestResource(JAVA_UNFORMATTED)); + setFile(target).toResource(JAVA_UNFORMATTED); } private void assertFormattedJava(String target) throws IOException { - assertThat(read(target)).isEqualTo(getTestResource(JAVA_FORMATTED)); + assertFile(target).sameAsResource(JAVA_FORMATTED); } private void assertUnformattedJava(String target) throws IOException { - assertThat(read(target)).isEqualTo(getTestResource(JAVA_UNFORMATTED)); + assertFile(target).sameAsResource(JAVA_UNFORMATTED); } private void writeFormattedScala(String target) throws IOException { - write(target, getTestResource(SCALA_FORMATTED)); + setFile(target).toResource(SCALA_FORMATTED); } private void writeUnformattedScala(String target) throws IOException { - write(target, getTestResource(SCALA_UNFORMATTED)); + setFile(target).toResource(SCALA_UNFORMATTED); } private void assertFormattedScala(String target) throws IOException { - assertThat(read(target)).isEqualTo(getTestResource(SCALA_FORMATTED)); + assertFile(target).sameAsResource(SCALA_FORMATTED); } private void assertUnformattedScala(String target) throws IOException { - assertThat(read(target)).isEqualTo(getTestResource(SCALA_UNFORMATTED)); + assertFile(target).sameAsResource(SCALA_UNFORMATTED); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationTest.java index d9f25a2bd1..524c03c29a 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationTest.java @@ -63,7 +63,7 @@ public class MavenIntegrationTest extends ResourceHarness { */ @Before public void gitAttributes() throws IOException { - write(".gitattributes", "* text eol=lf"); + setFile(".gitattributes").toContent("* text eol=lf"); // copy the mvnw resources copy("mvnw").setExecutable(true); copy("mvnw.cmd"); @@ -93,7 +93,7 @@ protected void writePom(String... configuration) throws IOException { protected void writePom(String[] executions, String[] configuration) throws IOException { String pomXmlContent = createPomXmlContent(executions, configuration); - write("pom.xml", pomXmlContent); + setFile("pom.xml").toContent(pomXmlContent); } protected MavenRunner mavenRunner() throws IOException { diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessCheckMojoTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessCheckMojoTest.java index cda89aba4f..df25ea4237 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessCheckMojoTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/SpotlessCheckMojoTest.java @@ -65,8 +65,8 @@ public void testSpotlessCheckBindingToVerifyPhase() throws Exception { } private void testSpotlessCheck(String fileName, String command, boolean expectError) throws Exception { - write("license.txt", getTestResource("license/TestLicense")); - write("src/main/java/com.github.youribonnaffe.gradle.format/Java8Test.java", getTestResource(fileName)); + setFile("license.txt").toResource("license/TestLicense"); + setFile("src/main/java/com.github.youribonnaffe.gradle.format/Java8Test.java").toResource(fileName); MavenRunner mavenRunner = mavenRunner().withArguments(command); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java index cf41bbbbc7..c0e7f784d2 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/generic/LicenseHeaderTest.java @@ -26,7 +26,7 @@ public class LicenseHeaderTest extends MavenIntegrationTest { @Test public void fromFile() throws Exception { - write("license.txt", getTestResource(KEY_LICENSE)); + setFile("license.txt").toResource(KEY_LICENSE); writePomWithJavaSteps( "", " ${basedir}/license.txt", @@ -48,7 +48,7 @@ public void fromContent() throws Exception { @Test public void fromFileGlobal() throws Exception { - write("license.txt", getTestResource(KEY_LICENSE)); + setFile("license.txt").toResource(KEY_LICENSE); writePom("", " ${basedir}/license.txt", "", @@ -58,7 +58,7 @@ public void fromFileGlobal() throws Exception { } private void runTest() throws Exception { - write("src/main/java/test.java", getTestResource("license/MissingLicense.test")); + setFile("src/main/java/test.java").toResource("license/MissingLicense.test"); mavenRunner().withArguments("spotless:apply").runNoError(); String actual = read("src/main/java/test.java"); assertThat(actual).isEqualTo(getTestResource("license/HasLicense.test")); diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java index 92e0fb201c..f97dc2d664 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/EclipseFormatStepTest.java @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.maven.java; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; import com.diffplug.spotless.maven.MavenIntegrationTest; @@ -30,13 +28,10 @@ public void testEclipse() throws Exception { " ${basedir}/formatter.xml", " 4.7.1", ""); + setFile("formatter.xml").toResource("java/eclipse/formatter.xml"); - write("src/main/java/test.java", getTestResource("java/eclipse/JavaCodeUnformatted.test")); - write("formatter.xml", getTestResource("java/eclipse/formatter.xml")); - + setFile("src/main/java/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/java/test.java"); - assertThat(actual).isEqualTo(getTestResource("java/eclipse/JavaCodeFormatted.test")); + assertFile("src/main/java/test.java").sameAsResource("java/eclipse/JavaCodeFormatted.test"); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java index c3b37d5a5c..e32fde7e00 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/GoogleJavaFormatTest.java @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.maven.java; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; import com.diffplug.spotless.maven.MavenIntegrationTest; @@ -29,12 +27,9 @@ public void specificVersionDefaultStyle() throws Exception { " 1.2", ""); - write("src/main/java/test.java", getTestResource("java/googlejavaformat/JavaCodeUnformatted.test")); - + setFile("src/main/java/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/java/test.java"); - assertThat(actual).isEqualTo(getTestResource("java/googlejavaformat/JavaCodeFormatted.test")); + assertFile("src/main/java/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); } @Test @@ -45,11 +40,8 @@ public void specificVersionSpecificStyle() throws Exception { " ", ""); - write("src/main/java/test.java", getTestResource("java/googlejavaformat/JavaCodeUnformatted.test")); - + setFile("src/main/java/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/java/test.java"); - assertThat(actual).isEqualTo(getTestResource("java/googlejavaformat/JavaCodeFormattedAOSP.test")); + assertFile("src/main/java/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormattedAOSP.test"); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java index 26bc618452..99a5bb219d 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/ImportOrderTest.java @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.maven.java; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; import com.diffplug.spotless.maven.MavenIntegrationTest; @@ -24,7 +22,7 @@ public class ImportOrderTest extends MavenIntegrationTest { @Test public void file() throws Exception { - write("import.properties", getTestResource("java/importsorter/import.properties")); + setFile("import.properties").toResource("java/importsorter/import.properties"); writePomWithJavaSteps( "", " ${basedir}/import.properties", @@ -42,9 +40,8 @@ public void order() throws Exception { } private void runTest() throws Exception { - write("src/main/java/test.java", getTestResource("java/importsorter/JavaCodeUnsortedImports.test")); + setFile("src/main/java/test.java").toResource("java/importsorter/JavaCodeUnsortedImports.test"); mavenRunner().withArguments("spotless:apply").runNoError(); - String actual = read("src/main/java/test.java"); - assertThat(actual).isEqualTo(getTestResource("java/importsorter/JavaCodeSortedImports.test")); + assertFile("src/main/java/test.java").sameAsResource("java/importsorter/JavaCodeSortedImports.test"); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java index c57ff55476..9ef2134582 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/java/RemoveUnusedImportsStepTest.java @@ -15,8 +15,6 @@ */ package com.diffplug.spotless.maven.java; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; import com.diffplug.spotless.maven.MavenIntegrationTest; @@ -26,11 +24,9 @@ public class RemoveUnusedImportsStepTest extends MavenIntegrationTest { @Test public void testRemoveUnusedInports() throws Exception { writePomWithJavaSteps(""); - write("src/main/java/test.java", getTestResource("java/removeunusedimports/JavaCodeWithPackageUnformatted.test")); + setFile("src/main/java/test.java").toResource("java/removeunusedimports/JavaCodeWithPackageUnformatted.test"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/java/test.java"); - assertThat(actual).isEqualTo(getTestResource("java/removeunusedimports/JavaCodeWithPackageFormatted.test")); + assertFile("src/main/java/test.java").sameAsResource("java/removeunusedimports/JavaCodeWithPackageFormatted.test"); } } diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java index b9a4c85e8a..d070a92f0f 100644 --- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java +++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/scala/ScalafmtTest.java @@ -15,23 +15,18 @@ */ package com.diffplug.spotless.maven.scala; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; import com.diffplug.spotless.maven.MavenIntegrationTest; public class ScalafmtTest extends MavenIntegrationTest { - @Test public void testScalafmtWithDefaultConfig() throws Exception { writePomWithScalaSteps(""); - write("src/main/scala/test.scala", getTestResource("scala/scalafmt/basic.dirty")); + setFile("src/main/scala/test.scala").toResource("scala/scalafmt/basic.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/scala/test.scala"); - assertThat(actual).isEqualTo(getTestResource("scala/scalafmt/basic.clean")); + assertFile("src/main/scala/test.scala").sameAsResource("scala/scalafmt/basic.clean"); } @Test @@ -40,12 +35,10 @@ public void testScalafmtWithCustomConfig() throws Exception { "", " ${project.basedir}/scalafmt.conf", ""); + setFile("scalafmt.conf").toResource("scala/scalafmt/scalafmt.conf"); - write("src/main/scala/test.scala", getTestResource("scala/scalafmt/basic.dirty")); - write("scalafmt.conf", getTestResource("scala/scalafmt/scalafmt.conf")); + setFile("src/main/scala/test.scala").toResource("scala/scalafmt/basic.dirty"); mavenRunner().withArguments("spotless:apply").runNoError(); - - String actual = read("src/main/scala/test.scala"); - assertThat(actual).isEqualTo(getTestResource("scala/scalafmt/basic.cleanWithCustomConf")); + assertFile("src/main/scala/test.scala").sameAsResource("scala/scalafmt/basic.cleanWithCustomConf"); } } diff --git a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java index 4cf6d5fe2a..859148ba0e 100644 --- a/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java +++ b/testlib/src/main/java/com/diffplug/spotless/ResourceHarness.java @@ -25,11 +25,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; import java.util.logging.Logger; import java.util.stream.Collectors; -import org.assertj.core.api.AbstractFileAssert; +import org.assertj.core.api.AbstractCharSequenceAssert; import org.assertj.core.api.Assertions; +import org.assertj.core.util.CheckReturnValue; import org.junit.Assert; import org.junit.ComparisonFailure; import org.junit.Rule; @@ -84,47 +87,8 @@ protected File newFile(String subpath) throws IOException { return new File(rootFolder(), subpath); } - /** Returns a random child of the root folder. */ - protected File newFile() throws IOException { - return folderDontUseDirectly.newFile().getCanonicalFile(); - } - - /** Writes the given content to the given path. */ - protected File write(String path, String... lines) throws IOException { - return write(path, LineEnding.UNIX, lines); - } - - protected File write(String path, LineEnding ending, String... lines) throws IOException { - return write(path, ending, StandardCharsets.UTF_8, lines); - } - - protected File write(String path, LineEnding ending, Charset encoding, String... lines) throws IOException { - String content; - if (lines.length == 1) { - content = lines[0]; - } else { - content = Arrays.stream(lines).collect(Collectors.joining(ending.str())) + ending.str(); - } - Path target = newFile(path).toPath(); - Files.createDirectories(target.getParent()); - Files.write(target, content.getBytes(encoding)); - return target.toFile(); - } - - protected AbstractFileAssert assertFile(String path) throws IOException { - return Assertions.assertThat(newFile(path)).usingCharset(StandardCharsets.UTF_8); - } - protected String read(String path) throws IOException { - return read(newFile(path).toPath()); - } - - protected String read(Path path) throws IOException { - return read(path, StandardCharsets.UTF_8); - } - - protected String read(String path, Charset encoding) throws IOException { - return read(newFile(path).toPath(), encoding); + return read(newFile(path).toPath(), StandardCharsets.UTF_8); } protected String read(Path path, Charset encoding) throws IOException { @@ -137,7 +101,7 @@ protected void replace(String path, String toReplace, String replaceWith) throws if (before.equals(after)) { throw new IllegalArgumentException("Replace was ineffective! '" + toReplace + "' was not found in " + path); } - write(path, after); + setFile(path).toContent(after); } /** Returns the contents of the given file from the src/test/resources directory. */ @@ -168,21 +132,6 @@ protected File createTestFile(String filename) throws IOException { return file; } - /** Returns a File (in a temporary folder) which has the given contents. */ - protected File createTestFile(String filename, String content) throws IOException { - File file = newFile(filename); - file.getParentFile().mkdirs(); - Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8)); - return file; - } - - /** Asserts that the given resource from the src/test/resources directory has the same content as the given file. */ - protected void assertFileContent(String expectedContent, File actual) throws IOException { - // This line thing is necessary for the tests to pass when Windows git screws up the line-endings - String actualContent = new String(Files.readAllBytes(actual.toPath()), StandardCharsets.UTF_8); - Assert.assertEquals(expectedContent, actualContent); - } - /** Reads the given resource from "before", applies the step, and makes sure the result is "after". */ protected void assertOnResources(FormatterStep step, String unformattedPath, String expectedPath) throws Throwable { assertOnResources(rawUnix -> step.format(rawUnix, new File("")), unformattedPath, expectedPath); @@ -199,4 +148,74 @@ protected void assertOnResources(FormatterFunc step, String unformattedPath, Str String expected = LineEnding.toUnix(getTestResource(expectedPath)); // unix-ified output Assert.assertEquals(expected, formatted); } + + @CheckReturnValue + protected ReadAsserter assertFile(String path) throws IOException { + return new ReadAsserter(newFile(path)); + } + + @CheckReturnValue + protected ReadAsserter assertFile(File file) throws IOException { + return new ReadAsserter(file); + } + + public static class ReadAsserter { + private final File file; + + private ReadAsserter(File file) { + this.file = file; + } + + public void hasContent(String expected) { + hasContent(expected, StandardCharsets.UTF_8); + } + + public void hasContent(String expected, Charset charset) { + Assertions.assertThat(file).usingCharset(charset).hasContent(expected); + } + + public void hasLines(String... lines) { + hasContent(Arrays.stream(lines).collect(Collectors.joining("\n"))); + } + + public void sameAsResource(String resource) throws IOException { + hasContent(getTestResource(resource)); + } + + public void matches(Consumer> conditions) throws IOException { + String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + conditions.accept(Assertions.assertThat(content)); + } + } + + protected WriteAsserter setFile(String path) throws IOException { + return new WriteAsserter(newFile(path)); + } + + public static class WriteAsserter { + private File file; + + private WriteAsserter(File file) { + file.getParentFile().mkdirs(); + this.file = Objects.requireNonNull(file); + } + + public File toLines(String... lines) throws IOException { + return toContent(Arrays.stream(lines).collect(Collectors.joining("\n"))); + } + + public File toContent(String content) throws IOException { + return toContent(content, StandardCharsets.UTF_8); + } + + public File toContent(String content, Charset charset) throws IOException { + Files.write(file.toPath(), content.getBytes(charset)); + return file; + } + + public File toResource(String path) throws IOException { + Files.write(file.toPath(), getTestResource(path).getBytes(StandardCharsets.UTF_8)); + return file; + } + } } diff --git a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java index 2517a3949d..b514a764fb 100644 --- a/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/FileSignatureTest.java @@ -26,7 +26,6 @@ import org.junit.Test; public class FileSignatureTest extends ResourceHarness { - private final static String[] inputPaths = {"A", "C", "C", "A", "B"}; private final static String[] expectedPathList = inputPaths; private final static String[] expectedPathSet = {"A", "B", "C"}; @@ -52,7 +51,7 @@ public void testFromSet() throws IOException { private List getTestFiles(final String[] paths) throws IOException { final List result = new ArrayList<>(paths.length); for (String path : paths) { - result.add(createTestFile(path, "")); + result.add(setFile(path).toContent("")); } return result; }