1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle;
21
22 import static com.google.common.truth.Truth.assertWithMessage;
23
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.util.List;
28 import java.util.stream.Stream;
29
30 import org.junit.jupiter.api.BeforeEach;
31 import org.junit.jupiter.params.ParameterizedTest;
32 import org.junit.jupiter.params.provider.MethodSource;
33
34 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
35
36 public class IndentationTrailingCommentsVerticalAlignmentTest {
37
38 private static final String INDENTATION_TEST_FILES_PATH =
39 "com/puppycrawl/tools/checkstyle/checks/indentation/indentation";
40
41 private int tabWidth;
42
43 @BeforeEach
44 public void setUp() {
45 tabWidth = 4;
46 }
47
48 @MethodSource("indentationTestFiles")
49 @ParameterizedTest
50 public final void testTrailingCommentsAlignment(Path testFile) throws IOException {
51 final int currentTabWidth = tabWidth;
52 final List<String> lines = Files.readAllLines(testFile);
53 int expectedStartIndex = -1;
54
55 for (int idx = 0; idx < lines.size(); idx++) {
56 final String line = lines.get(idx);
57 if (line.trim().startsWith("import ") || line.trim().startsWith("package ")) {
58 continue;
59 }
60 final int commentStartIndex = line.indexOf("//indent:");
61 if (commentStartIndex > 0) {
62 final String codePart = line.substring(0, commentStartIndex);
63 if (!codePart.isBlank()) {
64 int actualStartIndex =
65 CommonUtil.lengthExpandedTabs(line, commentStartIndex, currentTabWidth);
66
67
68 final long extraWidth = codePart.codePoints().filter(
69 Character::isSupplementaryCodePoint).count();
70 actualStartIndex -= Math.toIntExact(extraWidth);
71
72 if (expectedStartIndex == -1) {
73 expectedStartIndex = actualStartIndex;
74 }
75 else {
76 assertWithMessage(
77 "Trailing comment alignment mismatch in file: %s on line %s",
78 testFile, idx + 1)
79 .that(actualStartIndex)
80 .isEqualTo(expectedStartIndex);
81 }
82 }
83 }
84 }
85 }
86
87 private static Stream<Path> indentationTestFiles() {
88 final Path resourcesDir = Path.of("src", "test", "resources");
89 final Path indentationDir = resourcesDir.resolve(INDENTATION_TEST_FILES_PATH);
90 Stream<Path> result;
91 try (Stream<Path> testFiles = Files.walk(indentationDir)) {
92 final List<Path> collected = testFiles
93 .filter(path -> {
94 final String fileName = path.getFileName().toString();
95 return fileName.startsWith("InputIndentation")
96 && fileName.endsWith(".java");
97 }).toList();
98 result = collected.stream();
99 }
100 catch (IOException exception) {
101 assertWithMessage("Failed to find indentation test files")
102 .that(exception)
103 .isNull();
104 result = Stream.empty();
105 }
106 return result;
107 }
108 }