diff options
Diffstat (limited to 'core/src/test/java/com/google/googlejavaformat')
14 files changed, 267 insertions, 99 deletions
diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java index 8d71f4d..1a4ed09 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java @@ -19,12 +19,12 @@ import static com.google.common.truth.Truth8.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; -import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -39,7 +39,7 @@ public class CommandLineOptionsParserTest { @Test public void defaults() { - CommandLineOptions options = CommandLineOptionsParser.parse(Collections.<String>emptyList()); + CommandLineOptions options = CommandLineOptionsParser.parse(ImmutableList.of()); assertThat(options.files()).isEmpty(); assertThat(options.stdin()).isFalse(); assertThat(options.aosp()).isFalse(); @@ -159,7 +159,7 @@ public class CommandLineOptionsParserTest { CommandLineOptionsParser.parse(Arrays.asList("-lines=1:1", "-lines=1:1")); fail(); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).contains("overlap"); + assertThat(e).hasMessageThat().contains("overlap"); } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java index 0b81ba6..fc966fa 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -23,7 +23,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; @@ -98,8 +97,7 @@ public class DiagnosticTest { int result = main.format(path.toString()); assertThat(stdout.toString()).isEmpty(); - assertThat(stderr.toString()) - .contains("InvalidSyntax.java:1:35: error: illegal unicode escape"); + assertThat(stderr.toString()).contains("error: illegal unicode escape"); assertThat(result).isEqualTo(1); } @@ -156,7 +154,7 @@ public class DiagnosticTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -173,7 +171,7 @@ public class DiagnosticTest { public void parseErrorStdin() throws FormatterException, IOException, UsageException { String input = "class Foo { void f() {\n g() } }"; - InputStream inStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream inStream = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), inStream); @@ -190,7 +188,7 @@ public class DiagnosticTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -206,7 +204,7 @@ public class DiagnosticTest { @Test public void lexErrorStdin() throws FormatterException, IOException, UsageException { String input = "class Foo { void f() {\n g('foo'); } }"; - InputStream inStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream inStream = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), inStream); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java index 44ba639..61a4346 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java @@ -14,8 +14,7 @@ package com.google.googlejavaformat.java; -import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_VERSION; -import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; +import static com.google.common.collect.MoreCollectors.toOptional; import static com.google.common.io.Files.getFileExtension; import static com.google.common.io.Files.getNameWithoutExtension; import static java.nio.charset.StandardCharsets.UTF_8; @@ -23,7 +22,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableMultimap; import com.google.common.io.CharStreams; import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath.ResourceInfo; @@ -31,12 +30,12 @@ import com.google.googlejavaformat.Newlines; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.lang.reflect.Method; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.TreeMap; import org.junit.Test; import org.junit.runner.RunWith; @@ -47,8 +46,13 @@ import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class FormatterIntegrationTest { - private static final ImmutableSet<String> JAVA14_TESTS = - ImmutableSet.of("I477", "Records", "RSLs", "Var", "ExpressionSwitch"); + private static final ImmutableMultimap<Integer, String> VERSIONED_TESTS = + ImmutableMultimap.<Integer, String>builder() + .putAll(14, "I477", "Records", "RSLs", "Var", "ExpressionSwitch", "I574", "I594") + .putAll(15, "I603") + .putAll(16, "I588") + .putAll(17, "I683", "I684", "I696") + .build(); @Parameters(name = "{index}: {0}") public static Iterable<Object[]> data() throws IOException { @@ -76,7 +80,7 @@ public class FormatterIntegrationTest { case "output": outputs.put(baseName, contents); break; - default: + default: // fall out } } } @@ -87,7 +91,9 @@ public class FormatterIntegrationTest { String input = inputs.get(fileName); assertTrue("unmatched input", outputs.containsKey(fileName)); String expectedOutput = outputs.get(fileName); - if (JAVA14_TESTS.contains(fileName) && getMajor() < 14) { + Optional<Integer> version = + VERSIONED_TESTS.inverse().get(fileName).stream().collect(toOptional()); + if (version.isPresent() && Runtime.version().feature() < version.get()) { continue; } testInputs.add(new Object[] {fileName, input, expectedOutput}); @@ -95,21 +101,6 @@ public class FormatterIntegrationTest { return testInputs; } - private static int getMajor() { - try { - Method versionMethod = Runtime.class.getMethod("version"); - Object version = versionMethod.invoke(null); - return (int) version.getClass().getMethod("major").invoke(version); - } catch (Exception e) { - // continue below - } - int version = (int) Double.parseDouble(JAVA_CLASS_VERSION.value()); - if (49 <= version && version <= 52) { - return version - (49 - 5); - } - throw new IllegalStateException("Unknown Java version: " + JAVA_SPECIFICATION_VERSION.value()); - } - private final String name; private final String input; private final String expected; @@ -125,7 +116,9 @@ public class FormatterIntegrationTest { @Test public void format() { try { - String output = new Formatter().formatSource(input); + Formatter formatter = new Formatter(); + String output = formatter.formatSource(input); + output = StringWrapper.wrap(output, formatter); assertEquals("bad output for " + name, expected, output); } catch (FormatterException e) { fail(String.format("Formatter crashed on %s: %s", name, e.getMessage())); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java index 3f6e974..1653e56 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -16,6 +16,7 @@ package com.google.googlejavaformat.java; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; import com.google.common.base.Joiner; @@ -27,7 +28,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Rule; @@ -63,7 +63,7 @@ public final class FormatterTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -94,7 +94,7 @@ public final class FormatterTest { String input = "class Foo{\n" + "void f\n" + "() {\n" + "}\n" + "}\n"; String expectedOutput = "class Foo {\n" + " void f() {}\n" + "}\n"; - InputStream in = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream in = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -115,7 +115,7 @@ public final class FormatterTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -132,7 +132,7 @@ public final class FormatterTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -238,7 +238,7 @@ public final class FormatterTest { "", "import java.util.List;", "", - "import javax.annotations.Nullable;"); + "import javax.annotation.Nullable;"); @Test public void importsNotReorderedByDefault() throws FormatterException { @@ -262,7 +262,7 @@ public final class FormatterTest { String expect = "package com.google.example;\n\n" + "import java.util.List;\n" - + "import javax.annotations.Nullable;\n\n" + + "import javax.annotation.Nullable;\n\n" + "public class ExampleTest {\n" + " @Nullable List<?> xs;\n" + "}\n"; @@ -302,7 +302,7 @@ public final class FormatterTest { String inputResourceName = "com/google/googlejavaformat/java/testimports/A.input"; String input = getResource(inputResourceName); String expectedOutput = getResource(outputResourceName); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -315,14 +315,14 @@ public final class FormatterTest { assertThat(err.toString()).isEmpty(); assertThat(out.toString()).isEmpty(); - String output = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + String output = new String(Files.readAllBytes(path), UTF_8); assertThat(output).isEqualTo(expectedOutput); } private String getResource(String resourceName) throws IOException { try (InputStream stream = getClass().getClassLoader().getResourceAsStream(resourceName)) { assertWithMessage("Missing resource: " + resourceName).that(stream).isNotNull(); - return CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + return CharStreams.toString(new InputStreamReader(stream, UTF_8)); } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java new file mode 100644 index 0000000..15e4522 --- /dev/null +++ b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2021 Google Inc. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 com.google.googlejavaformat.java; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth8.assertThat; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ServiceLoader; +import java.util.spi.ToolProvider; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link GoogleJavaFormatToolProvider}. */ +@RunWith(JUnit4.class) +public class GoogleJavaFormatToolProviderTest { + + @Test + public void testUsageOutputAfterLoadingViaToolName() { + String name = "google-java-format"; + + assertThat( + ServiceLoader.load(ToolProvider.class).stream() + .map(ServiceLoader.Provider::get) + .map(ToolProvider::name)) + .contains(name); + + ToolProvider format = ToolProvider.findFirst(name).get(); + + StringWriter out = new StringWriter(); + StringWriter err = new StringWriter(); + + int result = format.run(new PrintWriter(out, true), new PrintWriter(err, true), "--help"); + + assertThat(result).isEqualTo(0); + + String usage = err.toString(); + + // Check that doc links are included. + assertThat(usage).containsMatch("http.*/google-java-format"); + assertThat(usage).contains("Usage: google-java-format"); + } +} diff --git a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java index 5a6b1f9..0b9dab2 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java @@ -313,7 +313,7 @@ public class ImportOrdererTest { "", "import java.util.List;", "", - "import javax.annotations.Nullable;", + "import javax.annotation.Nullable;", "", "import static org.junit.Assert.fail;", "import static com.google.truth.Truth.assertThat;", @@ -329,7 +329,7 @@ public class ImportOrdererTest { "", "import com.google.common.base.Preconditions;", "import java.util.List;", - "import javax.annotations.Nullable;", + "import javax.annotation.Nullable;", "import org.junit.runner.RunWith;", "import org.junit.runners.JUnit4;", "", @@ -527,6 +527,27 @@ public class ImportOrdererTest { "class Test {}", } }, + { + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + ";", + "import java.lang.Foo;", + "", + "interface Test {}", + }, + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + "import java.lang.Foo;", + "", + "interface Test {}", + } + } }; ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); @@ -799,7 +820,7 @@ public class ImportOrdererTest { "", "public class Blim {}", }, - }, + } }; ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); Arrays.stream(inputsOutputs).forEach(input -> builder.add(createRow(input))); diff --git a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java index f5103d9..6849c01 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java @@ -937,7 +937,9 @@ public final class JavadocFormattingTest { "class Test {}", }; String[] expected = { - "/** @param this is a param */", // + "/**", // + " * @param this is a param", + " */", "class Test {}", }; doFormatTest(input, expected); @@ -1415,4 +1417,33 @@ public final class JavadocFormattingTest { }; doFormatTest(input, expected); } + + @Test + public void missingSummaryFragment() { + String[] input = { + "public class Foo {", + " /**", + " * @return something.", + " */", + " public void setSomething() {}", + "", + " /**", + " * @hide", + " */", + " public void setSomething() {}", + "}", + }; + String[] expected = { + "public class Foo {", + " /**", + " * @return something.", + " */", + " public void setSomething() {}", + "", + " /** @hide */", + " public void setSomething() {}", + "}", + }; + doFormatTest(input, expected); + } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java index 613d391..ac3eb39 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java @@ -14,6 +14,8 @@ package com.google.googlejavaformat.java; +import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; +import static com.google.common.base.StandardSystemProperty.JAVA_HOME; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.nio.charset.StandardCharsets.UTF_8; @@ -50,6 +52,16 @@ public class MainTest { // PrintWriter instances used below are hard-coded to use system-default line separator. private final Joiner joiner = Joiner.on(System.lineSeparator()); + private static final ImmutableList<String> ADD_EXPORTS = + ImmutableList.of( + "--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", + "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED"); + @Test public void testUsageOutput() { StringWriter out = new StringWriter(); @@ -107,11 +119,13 @@ public class MainTest { public void testMain() throws Exception { Process process = new ProcessBuilder( - ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), - "-cp", - System.getProperty("java.class.path"), - Main.class.getName())) + ImmutableList.<String>builder() + .add(Paths.get(JAVA_HOME.value()).resolve("bin/java").toString()) + .addAll(ADD_EXPORTS) + .add("-cp") + .add(JAVA_CLASS_PATH.value()) + .add(Main.class.getName()) + .build()) .redirectError(Redirect.PIPE) .redirectOutput(Redirect.PIPE) .start(); @@ -308,7 +322,7 @@ public class MainTest { "@ParametersAreNonnullByDefault", "package com.google.common.labs.base;", "", - "import javax.annotation.CheckReturnValue;", + "import com.google.errorprone.annotations.CheckReturnValue;", "import javax.annotation.ParametersAreNonnullByDefault;", "", }; @@ -388,9 +402,9 @@ public class MainTest { assertThat(out.toString()) .isEqualTo( - b.toAbsolutePath().toString() + b.toAbsolutePath() + System.lineSeparator() - + c.toAbsolutePath().toString() + + c.toAbsolutePath() + System.lineSeparator()); assertThat(err.toString()).isEmpty(); } @@ -433,14 +447,16 @@ public class MainTest { Files.write(path, "class Test {\n}\n".getBytes(UTF_8)); Process process = new ProcessBuilder( - ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), - "-cp", - System.getProperty("java.class.path"), - Main.class.getName(), - "-n", - "--set-exit-if-changed", - "-")) + ImmutableList.<String>builder() + .add(Paths.get(JAVA_HOME.value()).resolve("bin/java").toString()) + .addAll(ADD_EXPORTS) + .add("-cp") + .add(JAVA_CLASS_PATH.value()) + .add(Main.class.getName()) + .add("-n") + .add("--set-exit-if-changed") + .add("-") + .build()) .redirectInput(path.toFile()) .redirectError(Redirect.PIPE) .redirectOutput(Redirect.PIPE) @@ -459,14 +475,16 @@ public class MainTest { Files.write(path, "class Test {\n}\n".getBytes(UTF_8)); Process process = new ProcessBuilder( - ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), - "-cp", - System.getProperty("java.class.path"), - Main.class.getName(), - "-n", - "--set-exit-if-changed", - path.toAbsolutePath().toString())) + ImmutableList.<String>builder() + .add(Paths.get(JAVA_HOME.value()).resolve("bin/java").toString()) + .addAll(ADD_EXPORTS) + .add("-cp") + .add(JAVA_CLASS_PATH.value()) + .add(Main.class.getName()) + .add("-n") + .add("--set-exit-if-changed") + .add(path.toAbsolutePath().toString()) + .build()) .redirectError(Redirect.PIPE) .redirectOutput(Redirect.PIPE) .start(); @@ -474,7 +492,7 @@ public class MainTest { String err = new String(ByteStreams.toByteArray(process.getErrorStream()), UTF_8); String out = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8); assertThat(err).isEmpty(); - assertThat(out).isEqualTo(path.toAbsolutePath().toString() + System.lineSeparator()); + assertThat(out).isEqualTo(path.toAbsolutePath() + System.lineSeparator()); assertThat(process.exitValue()).isEqualTo(1); } @@ -523,8 +541,8 @@ public class MainTest { "class T {", " String s =", " \"one long incredibly unbroken sentence moving from topic to topic so that no one had" - + " a\"", - " + \" chance to interrupt\";", + + " a chance\"", + " + \" to interrupt\";", "}", "", }; diff --git a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java index 57d55d7..b1142b3 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java @@ -25,7 +25,6 @@ import com.google.common.collect.Range; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -397,7 +396,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -429,7 +428,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -475,7 +474,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -521,7 +520,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -567,7 +566,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -714,7 +713,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("FormatterException.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -957,7 +956,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1081,7 +1080,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1108,7 +1107,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1133,7 +1132,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1156,7 +1155,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1177,7 +1176,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1429,7 +1428,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, lines(input).getBytes(StandardCharsets.UTF_8)); + Files.write(path, lines(input).getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1459,7 +1458,7 @@ public final class PartialFormattingTest { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, lines(input).getBytes(StandardCharsets.UTF_8)); + Files.write(path, lines(input).getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1505,7 +1504,7 @@ public final class PartialFormattingTest { private String formatMain(String input, String... args) throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Test.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1655,7 +1654,7 @@ public final class PartialFormattingTest { private String runFormatter(String input, String[] args) throws IOException, UsageException { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); diff --git a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java new file mode 100644 index 0000000..c0babb0 --- /dev/null +++ b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsCaseLabelsTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2021 Google Inc. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 com.google.googlejavaformat.java; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.googlejavaformat.java.RemoveUnusedImports.removeUnusedImports; +import static org.junit.Assume.assumeTrue; + +import com.google.common.base.Joiner; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests that unused import removal doesn't remove types used in case labels. */ +@RunWith(JUnit4.class) +public class RemoveUnusedImportsCaseLabelsTest { + @Test + public void preserveTypesInCaseLabels() throws FormatterException { + assumeTrue(Runtime.version().feature() >= 17); + String input = + Joiner.on('\n') + .join( + "package example;", + "import example.model.SealedInterface;", + "import example.model.TypeA;", + "import example.model.TypeB;", + "public class Main {", + " public void apply(SealedInterface sealedInterface) {", + " switch(sealedInterface) {", + " case TypeA a -> System.out.println(\"A!\");", + " case TypeB b -> System.out.println(\"B!\");", + " }", + " }", + "}"); + assertThat(removeUnusedImports(input)).isEqualTo(input); + } +} diff --git a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java index 1965feb..675bc88 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java @@ -258,7 +258,7 @@ public class RemoveUnusedImportsTest { }; ImmutableList.Builder<Object[]> builder = ImmutableList.builder(); for (String[][] inputAndOutput : inputsOutputs) { - assertThat(inputAndOutput.length).isEqualTo(2); + assertThat(inputAndOutput).hasLength(2); String[] input = inputAndOutput[0]; String[] output = inputAndOutput[1]; String[] parameters = { diff --git a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java index 89c94ea..53fb54d 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java @@ -395,8 +395,8 @@ public class StringWrapperIntegrationTest { @Test public void testCR() throws Exception { - assertThat(StringWrapper.wrap(40, formatter.formatSource(input.replace("\n", "\r")), formatter)) - .isEqualTo(output.replace("\n", "\r")); + assertThat(StringWrapper.wrap(40, formatter.formatSource(input.replace('\n', '\r')), formatter)) + .isEqualTo(output.replace('\n', '\r')); } @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java b/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java index 9d1e00a..3270bc6 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/TypeNameClassifierTest.java @@ -43,6 +43,7 @@ public final class TypeNameClassifierTest { assertThat(JavaCaseFormat.from("a_$")).isEqualTo(JavaCaseFormat.LOWERCASE); assertThat(JavaCaseFormat.from("_")).isEqualTo(JavaCaseFormat.LOWERCASE); assertThat(JavaCaseFormat.from("_A")).isEqualTo(JavaCaseFormat.UPPERCASE); + assertThat(JavaCaseFormat.from("A")).isEqualTo(JavaCaseFormat.UPPER_CAMEL); } private static Optional<Integer> getPrefix(String qualifiedName) { @@ -62,6 +63,7 @@ public final class TypeNameClassifierTest { assertThat(getPrefix("ClassName.CONST")).hasValue(1); assertThat(getPrefix("ClassName.varName")).hasValue(1); assertThat(getPrefix("ClassName.Inner.varName")).hasValue(2); + assertThat(getPrefix("com.R.foo")).hasValue(2); } @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java index 4fef207..38cac35 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java @@ -52,7 +52,7 @@ public class FormattingFilerTest { new Messager() { @Override public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg) { - logMessages.add(kind.toString() + ";" + msg); + logMessages.add(kind + ";" + msg); } @Override @@ -73,9 +73,9 @@ public class FormattingFilerTest { String file = Joiner.on('\n').join("package foo;", "public class Bar {"); FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler(), messager); - Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter(); - writer.write(file); - writer.close(); + try (Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter()) { + writer.write(file); + } assertThat(logMessages).containsExactly("NOTE;Error formatting foo.Bar"); } |