forked from checkstyle/checkstyle
/
CheckerTest.java
1566 lines (1335 loc) · 67.9 KB
/
CheckerTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2019 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import static com.puppycrawl.tools.checkstyle.Checker.EXCEPTION_MSG;
import static com.puppycrawl.tools.checkstyle.DefaultLogger.AUDIT_FINISHED_MESSAGE;
import static com.puppycrawl.tools.checkstyle.DefaultLogger.AUDIT_STARTED_MESSAGE;
import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.reflect.Whitebox;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.Context;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.ExternalResourceHolder;
import com.puppycrawl.tools.checkstyle.api.FileText;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.FilterSet;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck;
import com.puppycrawl.tools.checkstyle.checks.TranslationCheck;
import com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck;
import com.puppycrawl.tools.checkstyle.filters.SuppressionFilter;
import com.puppycrawl.tools.checkstyle.internal.testmodules.DebugAuditAdapter;
import com.puppycrawl.tools.checkstyle.internal.testmodules.DebugFilter;
import com.puppycrawl.tools.checkstyle.internal.testmodules.TestBeforeExecutionFileFilter;
import com.puppycrawl.tools.checkstyle.internal.testmodules.TestFileSetCheck;
import com.puppycrawl.tools.checkstyle.internal.utils.CloseAndFlushTestByteArrayOutputStream;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
public class CheckerTest extends AbstractModuleTestSupport {
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
private static Method getFireAuditFinished() throws NoSuchMethodException {
final Class<Checker> checkerClass = Checker.class;
final Method fireAuditFinished = checkerClass.getDeclaredMethod("fireAuditFinished");
fireAuditFinished.setAccessible(true);
return fireAuditFinished;
}
private static Method getFireAuditStartedMethod() throws NoSuchMethodException {
final Class<Checker> checkerClass = Checker.class;
final Method fireAuditStarted = checkerClass.getDeclaredMethod("fireAuditStarted");
fireAuditStarted.setAccessible(true);
return fireAuditStarted;
}
@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checker";
}
@Test
public void testDestroy() throws Exception {
final Checker checker = new Checker();
final DebugAuditAdapter auditAdapter = new DebugAuditAdapter();
checker.addListener(auditAdapter);
final TestFileSetCheck fileSet = new TestFileSetCheck();
checker.addFileSetCheck(fileSet);
final DebugFilter filter = new DebugFilter();
checker.addFilter(filter);
final TestBeforeExecutionFileFilter fileFilter = new TestBeforeExecutionFileFilter();
checker.addBeforeExecutionFileFilter(fileFilter);
// should remove all listeners, file sets, and filters
checker.destroy();
checker.process(Collections.singletonList(temporaryFolder.newFile()));
final SortedSet<LocalizedMessage> messages = new TreeSet<>();
messages.add(new LocalizedMessage(1, 0, "a Bundle", "message.key",
new Object[] {"arg"}, null, getClass(), null));
checker.fireErrors("Some File Name", messages);
assertFalse("Checker.destroy() doesn't remove listeners.", auditAdapter.wasCalled());
assertFalse("Checker.destroy() doesn't remove file sets.", fileSet.wasCalled());
assertFalse("Checker.destroy() doesn't remove filters.", filter.wasCalled());
assertFalse("Checker.destroy() doesn't remove file filters.", fileFilter.wasCalled());
}
@Test
public void testAddListener() throws Exception {
final Checker checker = new Checker();
final DebugAuditAdapter auditAdapter = new DebugAuditAdapter();
checker.addListener(auditAdapter);
// Let's try fire some events
getFireAuditStartedMethod().invoke(checker);
assertTrue("Checker.fireAuditStarted() doesn't call listener", auditAdapter.wasCalled());
assertTrue("Checker.fireAuditStarted() doesn't pass event", auditAdapter.wasEventPassed());
auditAdapter.resetListener();
getFireAuditFinished().invoke(checker);
assertTrue("Checker.fireAuditFinished() doesn't call listener", auditAdapter.wasCalled());
assertTrue("Checker.fireAuditFinished() doesn't pass event", auditAdapter.wasEventPassed());
auditAdapter.resetListener();
checker.fireFileStarted("Some File Name");
assertTrue("Checker.fireFileStarted() doesn't call listener", auditAdapter.wasCalled());
assertTrue("Checker.fireFileStarted() doesn't pass event", auditAdapter.wasEventPassed());
auditAdapter.resetListener();
checker.fireFileFinished("Some File Name");
assertTrue("Checker.fireFileFinished() doesn't call listener", auditAdapter.wasCalled());
assertTrue("Checker.fireFileFinished() doesn't pass event", auditAdapter.wasEventPassed());
auditAdapter.resetListener();
final SortedSet<LocalizedMessage> messages = new TreeSet<>();
messages.add(new LocalizedMessage(1, 0, "a Bundle", "message.key",
new Object[] {"arg"}, null, getClass(), null));
checker.fireErrors("Some File Name", messages);
assertTrue("Checker.fireErrors() doesn't call listener", auditAdapter.wasCalled());
assertTrue("Checker.fireErrors() doesn't pass event", auditAdapter.wasEventPassed());
}
@Test
public void testRemoveListener() throws Exception {
final Checker checker = new Checker();
final DebugAuditAdapter auditAdapter = new DebugAuditAdapter();
final DebugAuditAdapter aa2 = new DebugAuditAdapter();
checker.addListener(auditAdapter);
checker.addListener(aa2);
checker.removeListener(auditAdapter);
// Let's try fire some events
getFireAuditStartedMethod().invoke(checker);
assertTrue("Checker.fireAuditStarted() doesn't call listener", aa2.wasCalled());
assertFalse("Checker.fireAuditStarted() does call removed listener",
auditAdapter.wasCalled());
aa2.resetListener();
getFireAuditFinished().invoke(checker);
assertTrue("Checker.fireAuditFinished() doesn't call listener", aa2.wasCalled());
assertFalse("Checker.fireAuditFinished() does call removed listener",
auditAdapter.wasCalled());
aa2.resetListener();
checker.fireFileStarted("Some File Name");
assertTrue("Checker.fireFileStarted() doesn't call listener", aa2.wasCalled());
assertFalse("Checker.fireFileStarted() does call removed listener",
auditAdapter.wasCalled());
aa2.resetListener();
checker.fireFileFinished("Some File Name");
assertTrue("Checker.fireFileFinished() doesn't call listener", aa2.wasCalled());
assertFalse("Checker.fireFileFinished() does call removed listener",
auditAdapter.wasCalled());
aa2.resetListener();
final SortedSet<LocalizedMessage> messages = new TreeSet<>();
messages.add(new LocalizedMessage(1, 0, "a Bundle", "message.key",
new Object[] {"arg"}, null, getClass(), null));
checker.fireErrors("Some File Name", messages);
assertTrue("Checker.fireErrors() doesn't call listener", aa2.wasCalled());
assertFalse("Checker.fireErrors() does call removed listener", auditAdapter.wasCalled());
}
@Test
public void testAddBeforeExecutionFileFilter() throws Exception {
final Checker checker = new Checker();
final TestBeforeExecutionFileFilter filter = new TestBeforeExecutionFileFilter();
checker.addBeforeExecutionFileFilter(filter);
filter.resetFilter();
checker.process(Collections.singletonList(new File("dummy.java")));
assertTrue("Checker.acceptFileStarted() doesn't call filter", filter.wasCalled());
}
@Test
public void testRemoveBeforeExecutionFileFilter() throws Exception {
final Checker checker = new Checker();
final TestBeforeExecutionFileFilter filter = new TestBeforeExecutionFileFilter();
final TestBeforeExecutionFileFilter f2 = new TestBeforeExecutionFileFilter();
checker.addBeforeExecutionFileFilter(filter);
checker.addBeforeExecutionFileFilter(f2);
checker.removeBeforeExecutionFileFilter(filter);
f2.resetFilter();
checker.process(Collections.singletonList(new File("dummy.java")));
assertTrue("Checker.acceptFileStarted() doesn't call filter", f2.wasCalled());
assertFalse("Checker.acceptFileStarted() does call removed filter", filter.wasCalled());
}
@Test
public void testAddFilter() {
final Checker checker = new Checker();
final DebugFilter filter = new DebugFilter();
checker.addFilter(filter);
filter.resetFilter();
final SortedSet<LocalizedMessage> messages = new TreeSet<>();
messages.add(new LocalizedMessage(1, 0, "a Bundle", "message.key",
new Object[] {"arg"}, null, getClass(), null));
checker.fireErrors("Some File Name", messages);
assertTrue("Checker.fireErrors() doesn't call filter", filter.wasCalled());
}
@Test
public void testRemoveFilter() {
final Checker checker = new Checker();
final DebugFilter filter = new DebugFilter();
final DebugFilter f2 = new DebugFilter();
checker.addFilter(filter);
checker.addFilter(f2);
checker.removeFilter(filter);
f2.resetFilter();
final SortedSet<LocalizedMessage> messages = new TreeSet<>();
messages.add(new LocalizedMessage(1, 0, "a Bundle", "message.key",
new Object[] {"arg"}, null, getClass(), null));
checker.fireErrors("Some File Name", messages);
assertTrue("Checker.fireErrors() doesn't call filter", f2.wasCalled());
assertFalse("Checker.fireErrors() does call removed filter", filter.wasCalled());
}
@Test
public void testFileExtensions() throws Exception {
final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
final DebugAuditAdapter auditAdapter = new DebugAuditAdapter();
checker.addListener(auditAdapter);
final List<File> files = new ArrayList<>();
final File file = new File("file.pdf");
files.add(file);
final File otherFile = new File("file.java");
files.add(otherFile);
final String[] fileExtensions = {"java", "xml", "properties"};
checker.setFileExtensions(fileExtensions);
checker.setCacheFile(temporaryFolder.newFile().getPath());
final int counter = checker.process(files);
// comparing to 1 as there is only one legal file in input
final int numLegalFiles = 1;
final PropertyCacheFile cache = Whitebox.getInternalState(checker, "cacheFile");
assertEquals("There were more legal files than expected",
numLegalFiles, counter);
assertEquals("Audit was started on larger amount of files than expected",
numLegalFiles, auditAdapter.getNumFilesStarted());
assertEquals("Audit was finished on larger amount of files than expected",
numLegalFiles, auditAdapter.getNumFilesFinished());
assertNull("Cache shout not contain any file",
cache.get(new File("file.java").getCanonicalPath()));
}
@Test
public void testIgnoredFileExtensions() throws Exception {
final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
final DebugAuditAdapter auditAdapter = new DebugAuditAdapter();
checker.addListener(auditAdapter);
final List<File> allIgnoredFiles = new ArrayList<>();
final File ignoredFile = new File("file.pdf");
allIgnoredFiles.add(ignoredFile);
final String[] fileExtensions = {"java", "xml", "properties"};
checker.setFileExtensions(fileExtensions);
checker.setCacheFile(temporaryFolder.newFile().getPath());
final int counter = checker.process(allIgnoredFiles);
// comparing to 0 as there is no legal file in input
final int numLegalFiles = 0;
assertEquals("There were more legal files than expected",
numLegalFiles, counter);
assertEquals("Audit was started on larger amount of files than expected",
numLegalFiles, auditAdapter.getNumFilesStarted());
assertEquals("Audit was finished on larger amount of files than expected",
numLegalFiles, auditAdapter.getNumFilesFinished());
}
@Test
public void testSetters() {
// all that is set by reflection, so just make code coverage be happy
final Checker checker = new Checker();
checker.setClassLoader(getClass().getClassLoader());
checker.setBasedir("some");
checker.setSeverity("ignore");
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
checker.setFileExtensions((String[]) null);
checker.setFileExtensions(".java", "xml");
try {
checker.setCharset("UNKNOWN-CHARSET");
fail("Exception is expected");
}
catch (UnsupportedEncodingException ex) {
assertEquals("Error message is not expected",
"unsupported charset: 'UNKNOWN-CHARSET'", ex.getMessage());
}
}
@Test
public void testNoClassLoaderNoModuleFactory() {
final Checker checker = new Checker();
try {
checker.finishLocalSetup();
fail("Exception is expected");
}
catch (CheckstyleException ex) {
assertEquals("Error message is not expected",
"if no custom moduleFactory is set, moduleClassLoader must be specified",
ex.getMessage());
}
}
@Test
public void testNoModuleFactory() throws Exception {
final Checker checker = new Checker();
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
checker.setModuleClassLoader(classLoader);
checker.finishLocalSetup();
final Context actualCtx = Whitebox.getInternalState(checker, "childContext");
assertNotNull("Default module factory should be created when it is not specified",
actualCtx.get("moduleFactory"));
assertEquals("Invalid classLoader", classLoader, actualCtx.get("classLoader"));
}
@Test
public void testFinishLocalSetupFullyInitialized() throws Exception {
final Checker checker = new Checker();
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
checker.setModuleClassLoader(contextClassLoader);
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), contextClassLoader);
checker.setModuleFactory(factory);
checker.setBasedir("testBaseDir");
checker.setLocaleLanguage("it");
checker.setLocaleCountry("IT");
checker.finishLocalSetup();
final Context context = Whitebox.getInternalState(checker, "childContext");
assertEquals("Charset was different than expected",
System.getProperty("file.encoding", StandardCharsets.UTF_8.name()),
context.get("charset"));
assertEquals("Was used insufficient classloader",
contextClassLoader, context.get("classLoader"));
assertEquals("Severity is set to unexpected value",
"error", context.get("severity"));
assertEquals("Basedir is set to unexpected value",
"testBaseDir", context.get("basedir"));
final Field sLocale = LocalizedMessage.class.getDeclaredField("sLocale");
sLocale.setAccessible(true);
final Locale locale = (Locale) sLocale.get(null);
assertEquals("Locale is set to unexpected value", Locale.ITALY, locale);
}
@Test
public void testSetupChildExceptions() {
final Checker checker = new Checker();
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
final Configuration config = new DefaultConfiguration("java.lang.String");
try {
checker.setupChild(config);
fail("Exception is expected");
}
catch (CheckstyleException ex) {
assertEquals("Error message is not expected",
"java.lang.String is not allowed as a child in Checker", ex.getMessage());
}
}
@Test
public void testSetupChildInvalidProperty() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HiddenFieldCheck.class);
checkConfig.addAttribute("$$No such property", null);
try {
createChecker(checkConfig);
fail("Exception is expected");
}
catch (CheckstyleException ex) {
assertEquals("Error message is not expected",
"cannot initialize module com.puppycrawl.tools.checkstyle.TreeWalker"
+ " - cannot initialize module " + checkConfig.getName()
+ " - Property '$$No such property'"
+ " does not exist, please check the documentation", ex.getMessage());
}
}
@Test
public void testSetupChildListener() throws Exception {
final Checker checker = new Checker();
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
final Configuration config = new DefaultConfiguration(
DebugAuditAdapter.class.getCanonicalName());
checker.setupChild(config);
final List<AuditListener> listeners = Whitebox.getInternalState(checker, "listeners");
assertTrue("Invalid child listener class",
listeners.get(listeners.size() - 1) instanceof DebugAuditAdapter);
}
@Test
public void testDestroyCheckerWithWrongCacheFileNameLength() throws Exception {
final Checker checker = new Checker();
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
checker.configure(new DefaultConfiguration("default config"));
// We set wrong file name length in order to reproduce IOException on OS Linux, OS Windows.
// The maximum file name length which is allowed in most UNIX, Windows file systems is 255.
// See https://en.wikipedia.org/wiki/Filename;
checker.setCacheFile(String.format(Locale.ENGLISH, "%0300d", 0));
try {
checker.destroy();
fail("Exception did not happen");
}
catch (IllegalStateException ex) {
assertTrue("Cause of exception differs from IOException",
ex.getCause() instanceof IOException);
}
}
/**
* It is OK to have long test method name here as it describes the test purpose.
*/
@Test
public void testCacheAndCheckWhichDoesNotImplementExternalResourceHolderInterface()
throws Exception {
assertFalse("ExternalResourceHolder has changed his parent",
ExternalResourceHolder.class.isAssignableFrom(HiddenFieldCheck.class));
final DefaultConfiguration checkConfig = createModuleConfig(HiddenFieldCheck.class);
final DefaultConfiguration treeWalkerConfig = createModuleConfig(TreeWalker.class);
treeWalkerConfig.addChild(checkConfig);
final DefaultConfiguration checkerConfig = createRootConfig(treeWalkerConfig);
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
final File cacheFile = temporaryFolder.newFile();
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final File tmpFile = temporaryFolder.newFile("file.java");
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
verify(checkerConfig, tmpFile.getPath(), expected);
final Properties cacheAfterFirstRun = new Properties();
cacheAfterFirstRun.load(Files.newBufferedReader(cacheFile.toPath()));
// one more time to reuse cache
verify(checkerConfig, tmpFile.getPath(), expected);
final Properties cacheAfterSecondRun = new Properties();
cacheAfterSecondRun.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache from first run differs from second run cache",
cacheAfterFirstRun, cacheAfterSecondRun);
}
@Test
public void testWithCacheWithNoViolation() throws Exception {
final Checker checker = new Checker();
final PackageObjectFactory factory = new PackageObjectFactory(
new HashSet<>(), Thread.currentThread().getContextClassLoader());
checker.setModuleFactory(factory);
checker.configure(createModuleConfig(TranslationCheck.class));
final File cacheFile = temporaryFolder.newFile();
checker.setCacheFile(cacheFile.getPath());
checker.setupChild(createModuleConfig(TranslationCheck.class));
final File tmpFile = temporaryFolder.newFile("file.java");
final List<File> files = new ArrayList<>(1);
files.add(tmpFile);
checker.process(files);
// invoke destroy to persist cache
checker.destroy();
final Properties cache = new Properties();
cache.load(Files.newBufferedReader(cacheFile.toPath()));
// There should 2 objects in cache: processed file (file.java) and checker configuration.
final int expectedNumberOfObjectsInCache = 2;
assertEquals("Cache has unexpected size",
expectedNumberOfObjectsInCache, cache.size());
final String expectedConfigHash = "B8535A811CA90BE8B7A14D40BCA62B4FC2447B46";
assertEquals("Cache has unexpected hash",
expectedConfigHash, cache.getProperty(PropertyCacheFile.CONFIG_HASH_KEY));
assertNotNull("Cache file has null path",
cache.getProperty(tmpFile.getPath()));
}
@Test
public void testClearExistingCache() throws Exception {
final DefaultConfiguration checkerConfig = createRootConfig(null);
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
final File cacheFile = temporaryFolder.newFile();
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(getBriefUtLogger());
checker.clearCache();
// invoke destroy to persist cache
checker.destroy();
final Properties cacheAfterClear = new Properties();
cacheAfterClear.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache has unexpected size",
1, cacheAfterClear.size());
assertNotNull("Cache has null hash",
cacheAfterClear.getProperty(PropertyCacheFile.CONFIG_HASH_KEY));
final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath();
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
// file that should be audited is not in cache
verify(checker, pathToEmptyFile, pathToEmptyFile, expected);
final Properties cacheAfterSecondRun = new Properties();
cacheAfterSecondRun.load(Files.newBufferedReader(cacheFile.toPath()));
assertNotNull("Cache has null path",
cacheAfterSecondRun.getProperty(pathToEmptyFile));
assertEquals("Cash have changed it hash",
cacheAfterClear.getProperty(PropertyCacheFile.CONFIG_HASH_KEY),
cacheAfterSecondRun.getProperty(PropertyCacheFile.CONFIG_HASH_KEY)
);
final int expectedNumberOfObjectsInCacheAfterSecondRun = 2;
assertEquals("Cache has changed number of items",
expectedNumberOfObjectsInCacheAfterSecondRun, cacheAfterSecondRun.size());
}
@Test
public void testClearCache() throws Exception {
final DefaultConfiguration violationCheck =
createModuleConfig(DummyFileSetViolationCheck.class);
final DefaultConfiguration checkerConfig = new DefaultConfiguration("myConfig");
checkerConfig.addAttribute("charset", "UTF-8");
final File cacheFile = temporaryFolder.newFile();
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
checkerConfig.addChild(violationCheck);
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(getBriefUtLogger());
checker.process(Collections.singletonList(new File("dummy.java")));
checker.clearCache();
// invoke destroy to persist cache
final PropertyCacheFile cache = Whitebox.getInternalState(checker, "cacheFile");
cache.persist();
final Properties cacheAfterClear = new Properties();
cacheAfterClear.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache has unexpected size",
1, cacheAfterClear.size());
}
@Test
public void setFileExtension() {
final Checker checker = new Checker();
checker.setFileExtensions(".test1", "test2");
final String[] actual = Whitebox.getInternalState(checker, "fileExtensions");
assertArrayEquals("Extensions are not expected",
new String[] {".test1", ".test2"}, actual);
}
@Test
public void testClearCacheWhenCacheFileIsNotSet() {
// The idea of the test is to check that when cache file is not set,
// the invocation of clearCache method does not throw an exception.
final Checker checker = new Checker();
checker.clearCache();
assertNull("If cache file is not set the cache should default to null",
Whitebox.getInternalState(checker, "cacheFile"));
}
@Test
public void testCatchErrorInProcessFilesMethod() throws Exception {
// The idea of the test is to satisfy coverage rate.
// An Error indicates serious problems that a reasonable application should not try to
// catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
// we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
// that is why we use PowerMockito to reproduce them.
final File mock = PowerMockito.mock(File.class);
// Assume that I/O error is happened when we try to invoke 'lastModified()' method.
final String errorMessage = "Java Virtual Machine is broken"
+ " or has run out of resources necessary for it to continue operating.";
final Error expectedError = new IOError(new InternalError(errorMessage));
when(mock.lastModified()).thenThrow(expectedError);
when(mock.getAbsolutePath()).thenReturn("testFile");
final Checker checker = new Checker();
final List<File> filesToProcess = new ArrayList<>();
filesToProcess.add(mock);
try {
checker.process(filesToProcess);
fail("IOError is expected!");
}
// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
catch (Error error) {
assertThat("Error cause differs from IOError",
error.getCause(), instanceOf(IOError.class));
assertThat("Error cause is not InternalError",
error.getCause().getCause(), instanceOf(InternalError.class));
assertEquals("Error message is not expected",
errorMessage, error.getCause().getCause().getMessage());
}
}
@Test
public void testCatchErrorWithNoFileName() throws Exception {
// The idea of the test is to satisfy coverage rate.
// An Error indicates serious problems that a reasonable application should not try to
// catch, but due to issue https://github.com/checkstyle/checkstyle/issues/2285
// we catch errors in 'processFiles' method. Most such errors are abnormal conditions,
// that is why we use PowerMockito to reproduce them.
final File mock = PowerMockito.mock(File.class);
// Assume that I/O error is happened when we try to invoke 'lastModified()' method.
final String errorMessage = "Java Virtual Machine is broken"
+ " or has run out of resources necessary for it to continue operating.";
final Error expectedError = new IOError(new InternalError(errorMessage));
when(mock.lastModified()).thenThrow(expectedError);
final Checker checker = new Checker();
final List<File> filesToProcess = new ArrayList<>();
filesToProcess.add(mock);
try {
checker.process(filesToProcess);
fail("IOError is expected!");
}
// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
catch (Error error) {
assertThat("Error cause differs from IOError",
error.getCause(), instanceOf(IOError.class));
assertThat("Error cause is not InternalError",
error.getCause().getCause(), instanceOf(InternalError.class));
assertEquals("Error message is not expected",
errorMessage, error.getCause().getCause().getMessage());
}
}
@Test
public void testCatchErrorWithCache() throws Exception {
final File cacheFile = temporaryFolder.newFile();
final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final File mock = PowerMockito.mock(File.class);
final String errorMessage = "Java Virtual Machine is broken"
+ " or has run out of resources necessary for it to continue operating.";
final Error expectedError = new IOError(new InternalError(errorMessage));
when(mock.getAbsolutePath()).thenReturn("testFile");
when(mock.getAbsoluteFile()).thenThrow(expectedError);
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
final List<File> filesToProcess = new ArrayList<>();
filesToProcess.add(mock);
try {
checker.process(filesToProcess);
fail("IOError is expected!");
}
// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
catch (Error error) {
assertThat("Error cause differs from IOError",
error.getCause(), instanceOf(IOError.class));
assertEquals("Error message is not expected",
errorMessage, error.getCause().getCause().getMessage());
// destroy is called by Main
checker.destroy();
final Properties cache = new Properties();
cache.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache has unexpected size",
1, cache.size());
assertNull("testFile is not in cache",
cache.getProperty("testFile"));
}
}
@Test
public void testCatchErrorWithCacheWithNoFileName() throws Exception {
final File cacheFile = temporaryFolder.newFile();
final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration");
checkerConfig.addAttribute("charset", StandardCharsets.UTF_8.name());
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final File mock = PowerMockito.mock(File.class);
final String errorMessage = "Java Virtual Machine is broken"
+ " or has run out of resources necessary for it to continue operating.";
final Error expectedError = new IOError(new InternalError(errorMessage));
when(mock.getAbsolutePath()).thenThrow(expectedError);
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
final List<File> filesToProcess = new ArrayList<>();
filesToProcess.add(mock);
try {
checker.process(filesToProcess);
fail("IOError is expected!");
}
// -@cs[IllegalCatchExtended] Testing for catch Error is part of 100% coverage.
catch (Error error) {
assertThat("Error cause differs from IOError",
error.getCause(), instanceOf(IOError.class));
assertEquals("Error message is not expected",
errorMessage, error.getCause().getCause().getMessage());
// destroy is called by Main
checker.destroy();
final Properties cache = new Properties();
cache.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache has unexpected size",
1, cache.size());
}
}
/**
* It is OK to have long test method name here as it describes the test purpose.
*/
@Test
public void testCacheAndFilterWhichDoesNotImplementExternalResourceHolderInterface()
throws Exception {
assertFalse("ExternalResourceHolder has changed its parent",
ExternalResourceHolder.class.isAssignableFrom(DummyFilter.class));
final DefaultConfiguration filterConfig = createModuleConfig(DummyFilter.class);
final DefaultConfiguration checkerConfig = createRootConfig(filterConfig);
final File cacheFile = temporaryFolder.newFile();
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath();
verify(checkerConfig, pathToEmptyFile, expected);
final Properties cacheAfterFirstRun = new Properties();
cacheAfterFirstRun.load(Files.newBufferedReader(cacheFile.toPath()));
// One more time to use cache.
verify(checkerConfig, pathToEmptyFile, expected);
final Properties cacheAfterSecondRun = new Properties();
cacheAfterSecondRun.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals(
"Cache file has changed its path",
cacheAfterFirstRun.getProperty(pathToEmptyFile),
cacheAfterSecondRun.getProperty(pathToEmptyFile)
);
assertEquals(
"Cache has changed its hash",
cacheAfterFirstRun.getProperty(PropertyCacheFile.CONFIG_HASH_KEY),
cacheAfterSecondRun.getProperty(PropertyCacheFile.CONFIG_HASH_KEY)
);
final int expectedNumberOfObjectsInCache = 2;
assertEquals("Number of items in cache differs from expected",
expectedNumberOfObjectsInCache, cacheAfterFirstRun.size());
assertEquals("Number of items in cache differs from expected",
expectedNumberOfObjectsInCache, cacheAfterSecondRun.size());
}
/**
* It is OK to have long test method name here as it describes the test purpose.
*/
// -@cs[ExecutableStatementCount] This test needs to verify many things.
@Test
public void testCacheAndCheckWhichAddsNewResourceLocationButKeepsSameCheckerInstance()
throws Exception {
// Use case (https://github.com/checkstyle/checkstyle/pull/3092#issuecomment-218162436):
// Imagine that cache exists in a file. New version of Checkstyle appear.
// New release contains update to a some check to have additional external resource.
// User update his configuration and run validation as usually.
// Cache should not be reused.
final DynamicalResourceHolderCheck check = new DynamicalResourceHolderCheck();
final String firstExternalResourceLocation = getPath("InputCheckerImportControlOne.xml");
final String firstExternalResourceKey = PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX
+ firstExternalResourceLocation;
check.setFirstExternalResourceLocation(firstExternalResourceLocation);
final DefaultConfiguration checkerConfig = createRootConfig(null);
final File cacheFile = temporaryFolder.newFile();
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
final Checker checker = new Checker();
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.addFileSetCheck(check);
checker.addFilter(new DummyFilterSet());
checker.configure(checkerConfig);
checker.addListener(getBriefUtLogger());
final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath();
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
verify(checker, pathToEmptyFile, expected);
final Properties cacheAfterFirstRun = new Properties();
cacheAfterFirstRun.load(Files.newBufferedReader(cacheFile.toPath()));
final int expectedNumberOfObjectsInCacheAfterFirstRun = 4;
assertEquals("Number of items in cache differs from expected",
expectedNumberOfObjectsInCacheAfterFirstRun, cacheAfterFirstRun.size());
// Change a list of external resources which are used by the check
final String secondExternalResourceLocation = "InputCheckerImportControlTwo.xml";
final String secondExternalResourceKey = PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX
+ secondExternalResourceLocation;
check.setSecondExternalResourceLocation(secondExternalResourceLocation);
checker.addFileSetCheck(check);
checker.configure(checkerConfig);
verify(checker, pathToEmptyFile, expected);
final Properties cacheAfterSecondRun = new Properties();
cacheAfterSecondRun.load(Files.newBufferedReader(cacheFile.toPath()));
assertEquals("Cache file has changed its path",
cacheAfterFirstRun.getProperty(pathToEmptyFile),
cacheAfterSecondRun.getProperty(pathToEmptyFile)
);
assertEquals(
"Cache has changed its hash",
cacheAfterFirstRun.getProperty(PropertyCacheFile.CONFIG_HASH_KEY),
cacheAfterSecondRun.getProperty(PropertyCacheFile.CONFIG_HASH_KEY)
);
assertEquals("Cache has changed its resource key",
cacheAfterFirstRun.getProperty(firstExternalResourceKey),
cacheAfterSecondRun.getProperty(firstExternalResourceKey)
);
assertNotNull("Cache has null as a resource key",
cacheAfterFirstRun.getProperty(firstExternalResourceKey));
final int expectedNumberOfObjectsInCacheAfterSecondRun = 4;
assertEquals("Number of items in cache differs from expected",
expectedNumberOfObjectsInCacheAfterSecondRun, cacheAfterSecondRun.size());
assertNull("Cache has not null as a resource key",
cacheAfterFirstRun.getProperty(secondExternalResourceKey));
assertNotNull("Cache has null as a resource key",
cacheAfterSecondRun.getProperty(secondExternalResourceKey));
}
@Test
public void testClearLazyLoadCacheInDetailAST() throws Exception {
final DefaultConfiguration checkConfig1 =
createModuleConfig(CheckWhichDoesNotRequireCommentNodes.class);
final DefaultConfiguration checkConfig2 =
createModuleConfig(CheckWhichRequiresCommentNodes.class);
final DefaultConfiguration treeWalkerConfig = createModuleConfig(TreeWalker.class);
treeWalkerConfig.addChild(checkConfig1);
treeWalkerConfig.addChild(checkConfig2);
final DefaultConfiguration checkerConfig = createRootConfig(treeWalkerConfig);
final String filePath = getPath("InputCheckerClearDetailAstLazyLoadCache.java");
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
verify(checkerConfig, filePath, expected);
}
@Test
public void testCacheOnViolationSuppression() throws Exception {
final File cacheFile = temporaryFolder.newFile();
final DefaultConfiguration violationCheck =
createModuleConfig(DummyFileSetViolationCheck.class);
final DefaultConfiguration filterConfig = createModuleConfig(SuppressionFilter.class);
filterConfig.addAttribute("file", getPath("InputCheckerSuppressAll.xml"));
final DefaultConfiguration checkerConfig = createRootConfig(violationCheck);
checkerConfig.addAttribute("cacheFile", cacheFile.getPath());
checkerConfig.addChild(filterConfig);
final String fileViolationPath = temporaryFolder.newFile("ViolationFile.java").getPath();
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
verify(checkerConfig, fileViolationPath, expected);
try (InputStream input = Files.newInputStream(cacheFile.toPath())) {
final Properties details = new Properties();
details.load(input);
assertNotNull("suppressed violation file saved in cache",
details.getProperty(fileViolationPath));
}
}
@Test
public void testHaltOnException() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(CheckWhichThrowsError.class);
final String filePath = getPath("InputChecker.java");
try {
verify(checkConfig, filePath);
fail("Exception is expected");
}
catch (CheckstyleException ex) {
assertEquals("Error message is not expected",
"Exception was thrown while processing " + filePath, ex.getMessage());
}
}
@Test
public void testExceptionWithCache() throws Exception {
final File cacheFile = temporaryFolder.newFile();
final DefaultConfiguration checkConfig =
createModuleConfig(CheckWhichThrowsError.class);
final DefaultConfiguration treewalkerConfig =