forked from yegor256/qulice
/
CheckstyleValidatorTest.java
940 lines (879 loc) · 30.6 KB
/
CheckstyleValidatorTest.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
/*
* Copyright (c) 2011-2024 Qulice.com
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the Qulice.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.qulice.checkstyle;
import com.google.common.base.Joiner;
import com.qulice.spi.Environment;
import com.qulice.spi.Violation;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.cactoos.io.ResourceOf;
import org.cactoos.list.ListOf;
import org.cactoos.text.FormattedText;
import org.cactoos.text.IoCheckedText;
import org.cactoos.text.Joined;
import org.cactoos.text.TextOf;
import org.hamcrest.Description;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Test case for {@link CheckstyleValidator} class.
* @since 0.3
* @todo #412:30min Split this class into smaller ones and remove PMD
* exclude `TooManyMethods`. Good candidates for moving out of this class
* are all that use `validateCheckstyle` method.
* @checkstyle ClassDataAbstractionCoupling (800 lines)
* Can also be removed after splitting up this class into smaller ones.
*/
@SuppressWarnings(
{
"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals", "PMD.GodClass"
}
)
final class CheckstyleValidatorTest {
/**
* Name of property to set to change location of the license.
*/
private static final String LICENSE_PROP = "license";
/**
* Directory with classes.
*/
private static final String DIRECTORY = "src/main/java/foo";
/**
* License text.
*/
private static final String LICENSE = "Hello.";
/**
* Rule for testing.
*/
private License rule;
@BeforeEach
public void setRule() {
this.rule = new License();
}
/**
* CheckstyleValidator can catch checkstyle violations.
* @throws Exception If something wrong happens inside
*/
@Test
void catchesCheckstyleViolationsInLicense() throws Exception {
final Environment.Mock mock = new Environment.Mock();
final File license = this.rule.savePackageInfo(
new File(mock.basedir(), CheckstyleValidatorTest.DIRECTORY)
).withLines("License-1.", "", "License-2.")
.withEol("\n")
.file();
final String content =
// @checkstyle StringLiteralsConcatenation (4 lines)
// @checkstyle RegexpSingleline (1 line)
"/" + "**\n * License-3.\n *\n * License-2.\n */\n"
+ "package foo;\n"
+ "public class Foo { }\n";
final String name = "Foo.java";
final Environment env = mock.withParam(
CheckstyleValidatorTest.LICENSE_PROP,
this.toUrl(license)
).withFile(String.format("src/main/java/foo/%s", name), content);
final Collection<Violation> results =
new CheckstyleValidator(env)
.validate(env.files(name));
MatcherAssert.assertThat(
results,
Matchers.hasItem(
new ViolationMatcher(
"Line does not match expected header line of", name
)
)
);
}
/**
* CheckstyleValidator can accept instance method references.
* @throws Exception In case of error
*/
@Test
void acceptsInstanceMethodReferences() throws Exception {
this.runValidation(
"InstanceMethodRef.java", true
);
}
/**
* CheckstyleValidator can report error when parameter object is not
* documented.
* @throws Exception In case of error
*/
@Test
void reportsErrorWhenParameterObjectIsNotDocumented()
throws Exception {
this.validate(
"ParametrizedClass.java", false,
"Type Javadoc comment is missing @param <T> tag."
);
}
/**
* CheckstyleValidator reports an error when package declaration
* is line wrapped.
* @throws Exception when error.
*/
@Test
void reportsErrorWhenLineWrap()
throws Exception {
this.validate(
"LineWrapPackage.java", false,
"should not be line-wrapped"
);
}
/**
* CheckstyleValidator reports an error when indentation is not
* bigger than previous line by exactly 4.
* @throws Exception when error.
*/
@Test
void reportsErrorWhenIndentationIsIncorrect() throws Exception {
this.validate(
"InvalidIndentation.java",
false,
"Indentation (14) must be same or less than"
);
}
/**
* CheckstyleValidator does not report an error when there is no JavaDoc
* on method in JUnit tests.
* @throws Exception when error.
*/
@Test
void doesNotReportErrorWhenMissingJavadocInTests() throws Exception {
this.runValidation("MissingJavadocTest.java", true);
}
/**
* CheckstyleValidator reports an error when comment or Javadoc has too
* long line.
* @throws Exception when error.
*/
@Test
@SuppressWarnings("unchecked")
void reportsErrorWhenCommentOrJavadocIsTooLong() throws Exception {
final Collection<Violation> results =
this.runValidation("TooLongLines.java", false);
MatcherAssert.assertThat(
results,
Matchers.hasItems(
new ViolationMatcher(
"Line is longer than 100 characters (found 104)", ""
),
new ViolationMatcher(
"Line is longer than 100 characters (found 103)", ""
)
)
);
}
/**
* CheckstyleValidator can report Apache Commons {@code CharEncoding} class
* usages.
* @throws Exception when error.
*/
@Test
@SuppressWarnings("unchecked")
void reportsAllCharEncodingUsages() throws Exception {
final String message =
"Use java.nio.charset.StandardCharsets instead";
final String file = "DoNotUseCharEncoding.java";
final Collection<Violation> results = this.runValidation(
file, false
);
final String name = "RegexpSinglelineCheck";
MatcherAssert.assertThat(
results,
new IsIterableContainingInOrder<>(
new ListOf<>(
new ViolationMatcher(
message, file, "6", name
),
new ViolationMatcher(
message, file, "7", name
),
new ViolationMatcher(
message, file, "8", name
),
new ViolationMatcher(
message, file, "9", name
),
new ViolationMatcher(
message, file, "22", name
),
new ViolationMatcher(
message, file, "23", name
),
new ViolationMatcher(
message, file, "24", name
),
new ViolationMatcher(
message, file, "25", name
)
)
)
);
}
/**
* CheckstyleValidator accepts string literal which
* contains multiline comment.
* @throws Exception If test failed.
*/
@Test
void acceptsValidSingleLineComment() throws Exception {
this.runValidation(
"ValidSingleLineCommentCheck.java", true
);
}
/**
* CheckstyleValidator accepts the valid indentation
* refused by forceStrictCondition.
* @throws Exception when error.
*/
@Test
void acceptsValidIndentation() throws Exception {
this.runValidation(
"ValidIndentation.java", true
);
}
/**
* CheckstyleValidator reports an error when any method contains more
* than one return statement.
* @throws Exception when error.
*/
@Test
void reportsErrorOnMoreThanOneReturnStatement() throws Exception {
this.validate(
"ReturnCount.java", false,
"Return count is 2 (max allowed for non-void methods/lambdas is 1)"
);
}
/**
* CheckstyleValidator can accept default methods with final modifiers.
* @throws Exception In case of error
*/
@Test
void acceptsDefaultMethodsWithFinalModifiers() throws Exception {
this.runValidation(
"DefaultMethods.java", true
);
}
/**
* CheckstyleValidator can accept constant used in method annotation.
* @throws Exception In case of error
* @todo #447:30min Right now ConstantUsageCheck takes into account
* usage of constants inside method annotations, add handling of constants
* used in field and class annotations.
*/
@Test
void acceptsConstantUsedInMethodAnnotation() throws Exception {
this.runValidation("AnnotationConstant.java", true);
}
/**
* CheckstyleValidator can allow constructor parameters named just like
* fields.
* @throws Exception In case of error
*/
@Test
void acceptsConstructorParametersNamedJustLikeFields()
throws Exception {
final String file = "ConstructorParams.java";
final Collection<Violation> results = this.runValidation(file, false);
final String name = "HiddenFieldCheck";
MatcherAssert.assertThat(
results,
Matchers.allOf(
Matchers.hasItem(
new ViolationMatcher(
"'number' hides a field.", file, "29", name
)
),
Matchers.not(
Matchers.hasItem(
new ViolationMatcher(
"'number' hides a field.", file, "20", name
)
)
)
)
);
}
/**
* CheckstyleValidator allows local variables and catch parameters with
* names matching {@code ^[a-z]{3,12}$} pattern.
* Additionally, catch parameters can use name {@code ex}.
* @throws Exception In case of error
*/
@Test
@SuppressWarnings("unchecked")
void allowsOnlyProperlyNamedLocalVariables() throws Exception {
final String file = "LocalVariableNames.java";
final Collection<Violation> results = this.runValidation(
file, false
);
MatcherAssert.assertThat(results, Matchers.hasSize(10));
MatcherAssert.assertThat(
results,
Matchers.allOf(
Matchers.not(
Matchers.hasItems(
new ViolationMatcher("aaa", file),
new ViolationMatcher("twelveletter", file),
new ViolationMatcher("ise", file),
new ViolationMatcher("id", file),
new ViolationMatcher("parametername", file)
)
),
Matchers.hasItems(
new ViolationMatcher(
"Name 'prolongations' must match pattern", file
),
new ViolationMatcher(
"Name 'very_long_variable_id' must match pattern", file
),
new ViolationMatcher(
"Name 'camelCase' must match pattern", file
),
new ViolationMatcher(
"Name 'it' must match pattern", file
),
new ViolationMatcher(
"Name 'number1' must match pattern", file
),
new ViolationMatcher(
"Name 'ex' must match pattern", file
),
new ViolationMatcher(
"Name 'a' must match pattern", file
),
new ViolationMatcher(
"Name 'ae' must match pattern", file
),
new ViolationMatcher(
"Name 'e' must match pattern", file
),
new ViolationMatcher(
"Name 'it' must match pattern", file
)
)
)
);
}
/**
* CheckstyleValidator can allow only properly ordered Javadoc at-clauses.
* @throws Exception In case of error
*/
@Test
void allowsOnlyProperlyOrderedAtClauses() throws Exception {
final String file = "AtClauseOrder.java";
final Collection<Violation> results = this.runValidation(
file, false
);
final String message = "tags have to appear in the order";
final String name = "AtclauseOrderCheck";
MatcherAssert.assertThat(
results,
Matchers.contains(
new ViolationMatcher(
message, file, "14", name
),
new ViolationMatcher(
message, file, "21", name
),
new ViolationMatcher(
message, file, "48", name
),
new ViolationMatcher(
"Class Class should be declared as final.", file, "59", "FinalClassCheck"
)
)
);
}
/**
* CheckstyleValidator will fail if Windows EOL-s are used.
* @throws Exception If something wrong happens inside
*/
@Test
@Disabled
void passesWindowsEndsOfLineWithoutException() throws Exception {
this.validate("WindowsEol.java", false, "LICENSE found:");
}
/**
* Fail validation with Windows-style formatting of the license and
* Linux-style formatting of the sources.
* @throws Exception If something wrong happens inside
* @todo #61:30min This test and passesWindowsEndsOfLineWithoutException
* should be refactored to gather log4j logs and validate that they work
* correctly. (see changes done in #61)
*/
@Test
@Disabled
void testWindowsEndsOfLineWithLinuxSources() throws Exception {
this.runValidation("WindowsEolLinux.java", false);
}
/**
* CheckstyleValidator can allow proper indentation in complex annotations.
* @throws Exception If something wrong happens inside
*/
@Test
void allowsProperIndentationInAnnotations() throws Exception {
this.runValidation("AnnotationIndentation.java", true);
}
/**
* CheckstyleValidator can deny improper indentation in complex annotations.
* This is regression test for #411.
* @throws Exception If something wrong happens inside
*/
@Test
void rejectsImproperIndentationInAnnotations() throws Exception {
this.runValidation("AnnotationIndentationNegative.java", false);
}
/**
* Fail validation with extra semicolon in the end
* of try-with-resources head.
* @throws Exception If something wrong happens inside
*/
@Test
void testExtraSemicolonInTryWithResources() throws Exception {
this.validate(
"ExtraSemicolon.java", false,
"Extra semicolon in the end of try-with-resources head."
);
}
/**
* Correctly parses Record type.
* @throws Exception If something wrong happens inside
*/
@Test
void testSupportsRecordTypes() throws Exception {
this.runValidation("ValidRecord.java", true);
}
/**
* Accepts try-with-resources without extra semicolon
* at the end of the head.
* @throws Exception If something wrong happens inside
*/
@Test
void acceptsTryWithResourcesWithoutSemicolon() throws Exception {
this.runValidation("ValidSemicolon.java", true);
}
/**
* CheckstyleValidator cannot demand methods to be static in files with
* names ending with {@code ITCase}.
* @throws Exception If something wrong happens inside
*/
@Test
void acceptsNonStaticMethodsInIt() throws Exception {
this.runValidation("ValidIT.java", true);
}
/**
* CheckstyleValidator cannot demand methods to be static in files with
* names ending with {@code IT}.
* @throws Exception If something wrong happens inside
*/
@Test
void acceptsNonStaticMethodsInItCases() throws Exception {
this.runValidation("ValidITCase.java", true);
}
/**
* CheckstyleValidator does not produce errors when last thing
* in file are imports. The only exception that should be thrown is
* qulice ValidationException.
* @throws Exception In case of error
*/
@Test
void doesNotThrowExceptionIfImportsOnly() throws Exception {
final Environment.Mock mock = new Environment.Mock();
final File license = this.rule.savePackageInfo(
new File(mock.basedir(), CheckstyleValidatorTest.DIRECTORY)
).withLines("License-1.", "", "License-2.")
.withEol("\n")
.file();
final String crlf = "\r\n";
final String content = Joiner.on(crlf).join(
"package com.google;",
crlf,
"import java.util.*;"
);
final String name = "Foo.java";
final Environment env = mock.withParam(
CheckstyleValidatorTest.LICENSE_PROP,
this.toUrl(license)
).withFile(String.format("src/main/java/foo/%s", name), content);
final Collection<Violation> results =
new CheckstyleValidator(env).validate(env.files(name));
MatcherAssert.assertThat(
results,
Matchers.not(Matchers.<Violation>empty())
);
}
/**
* CheckstyleValidator can distinguish between valid and invalid
* catch parameter names.
* @throws Exception In case of error
*/
@Test
@SuppressWarnings({"unchecked", "PMD.AvoidDuplicateLiterals"})
void distinguishesValidCatchParameterNames() throws Exception {
final String file = "CatchParameterNames.java";
final Collection<Violation> results = this.runValidation(
file, false
);
MatcherAssert.assertThat(results, Matchers.hasSize(3));
final String name = "CatchParameterNameCheck";
MatcherAssert.assertThat(
results,
Matchers.hasItems(
new ViolationMatcher(
"Name 'ex_invalid_1' must match pattern", file, "26", name
),
new ViolationMatcher(
"Name '$xxx' must match pattern", file, "28", name
),
new ViolationMatcher(
"Name '_exp' must match pattern", file, "30", name
)
)
);
}
/**
* Test if URLs are valid despite having a line length over 80.
* @throws Exception In case of error
*/
@Test
void doesNotRejectUrlsInLongLines() throws Exception {
this.runValidation("UrlInLongLine.java", true);
}
/**
* CheckstyleValidator can allow spaces between methods of anonymous
* classes.
* @throws Exception In case of error
*/
@Test
void allowsSpacesBetweenMethodsOfAnonymousClasses()
throws Exception {
this.runValidation("BlankLinesOutsideMethodsPass.java", true);
}
/**
* CheckstyleValidator can reject spaces inside methods, regardless of
* whether they are inside of an anonymous method or not.
* @throws Exception In case of error
*/
@Test
@SuppressWarnings({"unchecked", "PMD.AvoidDuplicateLiterals"})
void rejectsSpacesInsideMethods() throws Exception {
final String file = "BlankLinesInsideMethodsFail.java";
final Collection<Violation> result = this.runValidation(
file, false
);
final String name = "EmptyLinesCheck";
final String message = "Empty line inside method";
MatcherAssert.assertThat(
result,
Matchers.hasItems(
new ViolationMatcher(message, file, "15", name),
new ViolationMatcher(message, file, "19", name),
new ViolationMatcher(message, file, "21", name),
new ViolationMatcher(message, file, "25", name),
new ViolationMatcher(message, file, "28", name),
new ViolationMatcher(message, file, "32", name),
new ViolationMatcher(message, file, "34", name),
new ViolationMatcher(message, file, "38", name),
new ViolationMatcher(message, file, "41", name),
new ViolationMatcher(message, file, "48", name),
new ViolationMatcher(message, file, "50", name),
new ViolationMatcher(message, file, "52", name)
)
);
}
/**
* CheckstyleValidator can reject uppercase abbreviations in naming
* outside of final static fields.
*
* @throws Exception In case of error
*/
@Test
@SuppressWarnings("unchecked")
void rejectsUppercaseAbbreviations() throws Exception {
final String file = "InvalidAbbreviationAsWordInNameXML.java";
final Collection<Violation> results = this.runValidation(
file, false
);
final String name = "AbbreviationAsWordInNameCheck";
final String message = new Joined(
" ",
"Abbreviation in name '%s'",
"must contain no more than '2' consecutive capital letters."
).asString();
MatcherAssert.assertThat(
results,
Matchers.hasItems(
new ViolationMatcher(
String.format(
message, "InvalidAbbreviationAsWordInNameXML"
),
file, "11", name
),
new ViolationMatcher(
String.format(message, "InvalidHTML"), file,
"15", name
)
)
);
}
/**
* CheckstyleValidator can allow IT as an uppercase abbreviation.
*
* @throws Exception In case of error
*/
@Test
void allowsITUppercaseAbbreviation() throws Exception {
this.runValidation("ValidAbbreviationAsWordInNameIT.java", true);
}
/**
* CheckstyleValidator can allow final static fields and overrides
* to have uppercase abbreviations.
*
* @throws Exception In case of error
*/
@Test
void allowsUppercaseAbbreviationExceptions() throws Exception {
this.runValidation("ValidAbbreviationAsWordInName.java", true);
}
/**
* CheckstyleValidator can allow final static fields and overrides
* to have uppercase abbreviations.
*
* @throws Exception In case of error
*/
@Disabled
@Test
void checkLambdaAndGenericsAtEndOfLine() throws Exception {
this.runValidation("ValidLambdaAndGenericsAtEndOfLine.java", true);
}
/**
* CheckstyleValidator can reject non diamond operator usage.
* @throws Exception If error
*/
@Test
void rejectsNonDiamondOperatorUsage() throws Exception {
final String file = "InvalidDiamondsUsage.java";
final String name = "DiamondOperatorCheck";
final String message = "Use diamond operator";
MatcherAssert.assertThat(
this.runValidation(file, false),
Matchers.hasItems(
new ViolationMatcher(message, file, "19", name),
new ViolationMatcher(message, file, "29", name)
)
);
}
/**
* CheckstyleValidator can allow diamond operator usage.
* @throws Exception If error
*/
@Test
void allowsDiamondOperatorUsage() throws Exception {
this.runValidation("ValidDiamondsUsage.java", true);
}
/**
* CheckstyleValidator allows class name instead of diamond in case
* of return statement.
* @throws Exception If error
*/
@Test
void allowsFullGenericOperatorUsage() throws Exception {
this.runValidation("DiamondUsageNotNeeded.java", true);
}
/**
* CheckstyleValidator can allow usage of string literals on either sides.
* E.g. both {@code txt.equals("contents")}
* and {@code "contents".equals(txt)} are valid.
* @throws Exception If error
*/
@Test
void allowsStringLiteralsOnBothSideInComparisons()
throws Exception {
this.runValidation("ValidLiteralComparisonCheck.java", true);
}
/**
* Convert file name to URL.
* @param file The file
* @return The URL
*/
private String toUrl(final File file) {
return String.format("file:%s", file);
}
/**
* Validates that checkstyle reported given violation.
* @param file File to check.
* @param result Expected validation result.
* @param message Message to match
* @throws Exception In case of error
*/
private void validate(final String file, final boolean result,
final String message) throws Exception {
MatcherAssert.assertThat(
this.runValidation(file, result),
Matchers.hasItem(
new ViolationMatcher(
message, file
)
)
);
}
/**
* Returns string with Checkstyle validation results.
* @param file File to check.
* @param passes Whether validation is expected to pass.
* @return String containing validation results in textual form.
* @throws IOException In case of error
*/
private Collection<Violation> runValidation(final String file,
final boolean passes) throws IOException {
final Environment.Mock mock = new Environment.Mock();
final File license = this.rule.savePackageInfo(
new File(mock.basedir(), CheckstyleValidatorTest.DIRECTORY)
).withLines(CheckstyleValidatorTest.LICENSE)
.withEol("\n").file();
final Environment env = mock.withParam(
CheckstyleValidatorTest.LICENSE_PROP,
this.toUrl(license)
)
.withFile(
String.format("src/main/java/foo/%s", file),
new IoCheckedText(
new TextOf(
new ResourceOf(
new FormattedText("com/qulice/checkstyle/%s", file)
)
)
).asString()
);
final Collection<Violation> results =
new CheckstyleValidator(env).validate(
env.files(file)
);
if (passes) {
MatcherAssert.assertThat(
results,
Matchers.<Violation>empty()
);
} else {
MatcherAssert.assertThat(
results,
Matchers.not(Matchers.<Violation>empty())
);
}
return results;
}
/**
* Validation results matcher.
*
* @since 0.1
*/
private static final class ViolationMatcher extends
TypeSafeMatcher<Violation> {
/**
* Message to check.
*/
private final String message;
/**
* File to check.
*/
private final String file;
/**
* Expected line.
*/
private final String line;
/**
* Check name.
*/
private final String check;
/**
* Constructor.
* @param message Message to check
* @param file File to check
* @param line Line to check
* @param check Check name
* @checkstyle ParameterNumber (3 lines)
*/
ViolationMatcher(final String message, final String file,
final String line, final String check) {
super();
this.message = message;
this.file = file;
this.line = line;
this.check = check;
}
/**
* Constructor.
* @param message Message to check
* @param file File to check
*/
ViolationMatcher(final String message, final String file) {
this(message, file, "", "");
}
@Override
public boolean matchesSafely(final Violation item) {
return item.message().contains(this.message)
&& item.file().endsWith(this.file)
&& this.lineMatches(item)
&& this.checkMatches(item);
}
@Override
public void describeTo(final Description description) {
description.appendText("doesn't match");
}
/**
* Check name matches.
* @param item Item to check.
* @return True if check name matches.
*/
private boolean checkMatches(final Violation item) {
return this.check.isEmpty()
|| !this.check.isEmpty() && item.name().equals(this.check);
}
/**
* Check that given line matches.
* @param item Item to check.
* @return True if line matches.
*/
private boolean lineMatches(final Violation item) {
return this.line.isEmpty()
|| !this.line.isEmpty() && item.lines().equals(this.line);
}
}
}