View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks;
21  
22  import static com.google.common.truth.Truth.assertWithMessage;
23  import static com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck.MSG_IO_EXCEPTION_KEY;
24  import static com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck.MSG_KEY;
25  
26  import java.io.File;
27  import java.io.IOException;
28  import java.io.InputStream;
29  import java.nio.file.Files;
30  import java.nio.file.NoSuchFileException;
31  import java.util.Collections;
32  import java.util.SortedSet;
33  
34  import org.junit.jupiter.api.Test;
35  
36  import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
37  import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
38  import com.puppycrawl.tools.checkstyle.api.FileText;
39  import com.puppycrawl.tools.checkstyle.api.Violation;
40  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
41  
42  public class OrderedPropertiesCheckTest extends AbstractModuleTestSupport {
43  
44      @Override
45      protected String getPackageLocation() {
46          return "com/puppycrawl/tools/checkstyle/checks/orderedproperties";
47      }
48  
49      /**
50       * Tests the ordinal work of a check.
51       * Test of sub keys, repeating key pairs in wrong order
52       */
53      @Test
54      public void testDefault() throws Exception {
55          final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
56          final String[] expected = {
57              "8: " + getCheckMessage(MSG_KEY, "key1", "key2"),
58              "11: " + getCheckMessage(MSG_KEY, "B", "key4"),
59              "14: " + getCheckMessage(MSG_KEY, "key3", "key5"),
60              "17: " + getCheckMessage(MSG_KEY, "key3", "key5"),
61          };
62          verify(checkConfig, getPath("InputOrderedProperties.properties"), expected);
63      }
64  
65      @Test
66      public void testKeysOnly() throws Exception {
67          final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
68          final String[] expected = {
69              "3: " + getCheckMessage(MSG_KEY, "key1", "key2"),
70          };
71          verify(checkConfig, getPath("InputOrderedProperties1OrderKey.properties"), expected);
72      }
73  
74      @Test
75      public void testEmptyKeys() throws Exception {
76          final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
77          final String[] expected = {
78              "3: " + getCheckMessage(MSG_KEY, "key11", "key2"),
79          };
80          verify(checkConfig, getPath("InputOrderedProperties2EmptyValue.properties"), expected);
81      }
82  
83      @Test
84      public void testMalformedValue() throws Exception {
85          final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
86          final String fileName =
87                  getPath("InputOrderedProperties3MalformedValue.properties");
88  
89          verify(checkConfig, fileName, "1: "
90                  + getCheckMessage(MSG_IO_EXCEPTION_KEY, fileName, "Malformed \\uxxxx encoding."));
91      }
92  
93      @Test
94      public void testCommentsMultiLine() throws Exception {
95          final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
96          final String[] expected = {
97              "5: " + getCheckMessage(MSG_KEY, "aKey", "multi.line"),
98          };
99          verify(checkConfig, getPath("InputOrderedProperties5CommentsMultiLine.properties"),
100                 expected);
101     }
102 
103     @Test
104     public void testLineNumberRepeatingPreviousKey() throws Exception {
105         final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
106         final String[] expected = {
107             "3: " + getCheckMessage(MSG_KEY, "a", "b"),
108         };
109         verify(checkConfig, getPath("InputOrderedProperties6RepeatingPreviousKey.properties"),
110                 expected);
111     }
112 
113     @Test
114     public void testShouldNotProcessFilesWithWrongFileExtension() throws Exception {
115         final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
116         final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
117         verify(checkConfig, getPath("InputOrderedProperties.txt"), expected);
118     }
119 
120     /**
121      * Tests IO exception, that can occur during reading of properties file.
122      */
123     @Test
124     public void testIoException() throws Exception {
125         final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
126         final OrderedPropertiesCheck check = new OrderedPropertiesCheck();
127         check.configure(checkConfig);
128         final String fileName =
129                 getPath("InputOrderedPropertiesCheckNotExisting.properties");
130         final File file = new File(fileName);
131         final FileText fileText = new FileText(file, Collections.emptyList());
132         final SortedSet<Violation> violations =
133                 check.process(file, fileText);
134         assertWithMessage("Wrong violations count")
135                 .that(violations)
136                 .hasSize(1);
137         final Violation violation = violations.iterator().next();
138         final String retrievedMessage = violations.iterator().next().getKey();
139         assertWithMessage("violation key is not valid")
140                 .that(retrievedMessage)
141                 .isEqualTo("unable.open.cause");
142         assertWithMessage("violation is not valid")
143                 .that(getCheckMessage(MSG_IO_EXCEPTION_KEY, fileName, getFileNotFoundDetail(file)))
144                 .isEqualTo(violation.getViolation());
145     }
146 
147     /**
148      * This test validates the PIT mutation of getIndex().
149      * Here the for statement for
150      * (int index = startLineNo; index < fileText.size(); index++)
151      * will change to
152      * for (int index = startLineNo; true; index++)
153      * By creating a FileText having no lines it makes sure that
154      * fileText.size() returning zero size.
155      * This will keep the for loop intact.
156      */
157     @Test
158     public void testKeepForLoopIntact() throws Exception {
159 
160         final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
161         final OrderedPropertiesCheck check = new OrderedPropertiesCheck();
162         check.configure(checkConfig);
163         final String fileName =
164                 getPath("InputOrderedProperties2EmptyValue.properties");
165         final File file = new File(fileName);
166         final FileText fileText = new FileText(file, Collections.emptyList());
167         final SortedSet<Violation> violations = check.process(file, fileText);
168 
169         assertWithMessage("Wrong violations count")
170                 .that(violations)
171                 .hasSize(1);
172     }
173 
174     @Test
175     public void testFileExtension() {
176 
177         final OrderedPropertiesCheck check = new OrderedPropertiesCheck();
178         assertWithMessage("File extension should be set")
179                 .that(".properties")
180                 .isEqualTo(check.getFileExtensions()[0]);
181     }
182 
183     @Test
184     public void test() throws Exception {
185         final DefaultConfiguration checkConfig = createModuleConfig(OrderedPropertiesCheck.class);
186         final String[] expected = {
187             "3: " + getCheckMessage(MSG_KEY, " A ", " B"),
188         };
189         verify(checkConfig, getPath("InputOrderedProperties2.properties"), expected);
190     }
191 
192     /**
193      * Method generates NoSuchFileException details. It tries to open a file that does not exist.
194      *
195      * @param file to be opened
196      * @return localized detail message of {@link NoSuchFileException}
197      */
198     private static String getFileNotFoundDetail(File file) {
199         // Create exception to know detail message we should wait in LocalisedMessage
200         try (InputStream stream = Files.newInputStream(file.toPath())) {
201             throw new IllegalStateException("File " + file.getPath() + " should not exist");
202         }
203         catch (IOException ex) {
204             return ex.getLocalizedMessage();
205         }
206     }
207 }