-
Notifications
You must be signed in to change notification settings - Fork 111
/
PmdValidatorTest.java
732 lines (686 loc) · 23.9 KB
/
PmdValidatorTest.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
/*
* Copyright (c) 2011-2023 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.pmd;
import com.google.common.base.Joiner;
import com.jcabi.matchers.RegexMatchers;
import com.qulice.pmd.rules.ProhibitPlainJunitAssertionsRule;
import com.qulice.spi.Environment;
import com.qulice.spi.Violation;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsEqual;
import org.hamcrest.core.IsNot;
import org.junit.jupiter.api.Test;
/**
* Test case for {@link PmdValidator} class.
* @since 0.3
*/
@SuppressWarnings("PMD.TooManyMethods")
public final class PmdValidatorTest {
/**
* Error message for forbidding access to static fields
* other than with a static way.
* @checkstyle LineLength (2 lines)
*/
private static final String STATIC_ACCESS = "%s\\[\\d+-\\d+\\]: Static fields should be accessed in a static way \\[CLASS_NAME.FIELD_NAME\\]\\.";
/**
* Error message for forbidding access to static members
* via instance reference using 'this' keyword.
* @checkstyle LineLength (2 lines)
*/
private static final String STATIC_VIA_THIS = "%s\\[\\d+-\\d+\\]: Static members should be accessed in a static way \\[CLASS_NAME.FIELD_NAME\\], not via instance reference.";
/**
* Error message for forbidding instructions inside a constructor
* other than field initialization or call to other constructors.
* @checkstyle LineLength (2 lines)
*/
private static final String CODE_IN_CON = "%s\\[\\d+-\\d+\\]: Only field initialization or call to other constructors in a constructor";
/**
* Pattern for non-constructor field initialization.
* @checkstyle LineLength (2 lines)
*/
private static final String NO_CON_INIT = "%s\\[\\d+-\\d+\\]: Avoid doing field initialization outside constructor.";
/**
* Pattern multiple constructors field initialization.
* @checkstyle LineLength (2 lines)
*/
private static final String MULT_CON_INIT = "%s\\[\\d+-\\d+\\]: Avoid field initialization in several constructors.";
/**
* Template for string inside brackets.
*/
private static final String BRACKETS = "(%s)";
/**
* Pattern using plain JUnit assertions.
*/
private static final String PLAIN_ASSERTIONS =
"Avoid using Plain JUnit assertions";
/**
* Error message used to inform about using public static method.
*/
private static final String STATIC_METHODS =
"Public static methods are prohibited";
/**
* Error text for Files.createFile.
*/
private static final String FILES_CREATE_ERR =
// @checkstyle LineLength (1 line)
"Files.createFile should not be used in tests, replace them with @Rule TemporaryFolder";
/**
* PmdValidator can find violations in Java file(s).
* @throws Exception If something wrong happens inside.
*/
@Test
public void findsProblemsInJavaFiles() throws Exception {
final String file = "src/main/java/Main.java";
final Environment env = new Environment.Mock()
.withFile(file, "class Main { int x = 0; }");
MatcherAssert.assertThat(
new PmdValidator(env).validate(
Collections.singletonList(new File(env.basedir(), file))
),
Matchers.not(Matchers.<Violation>empty())
);
}
/**
* PmdValidator can understand method references.
* @throws Exception If something wrong happens inside.
*/
@Test
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public void understandsMethodReferences() throws Exception {
final String file = "src/main/java/Other.java";
final Environment env = new Environment.Mock().withFile(
file,
Joiner.on('\n').join(
"import java.util.ArrayList;",
"class Other {",
" public static void test() {",
" new ArrayList<String>().forEach(Other::other);",
" }",
" private static void other(String some) {// body}",
"}"
)
);
final Collection<Violation> violations = new PmdValidator(env).validate(
Collections.singletonList(new File(env.basedir(), file))
);
MatcherAssert.assertThat(
violations,
Matchers.<Violation>empty()
);
}
/**
* PmdValidator does not think that constant is unused when it is used
* just from the inner class.
* @throws Exception If something wrong happens inside.
*/
@Test
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public void doesNotComplainAboutConstantsInInnerClasses() throws Exception {
final String file = "src/main/java/foo/Foo.java";
final Environment env = new Environment.Mock().withFile(
file,
Joiner.on('\n').join(
"package foo;",
"interface Foo {",
" final class Bar implements Foo {",
" private static final Pattern TEST =",
" Pattern.compile(\"hey\");",
" public String doSomething() {",
" return Foo.Bar.TEST.toString();",
" }",
" }",
"}"
)
);
MatcherAssert.assertThat(
new PmdValidator(env).validate(
Collections.singletonList(new File(env.basedir(), file))
),
Matchers.<Violation>empty()
);
}
/**
* PmdValidator can allow field initialization when constructor is missing.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsFieldInitializationWhenConstructorIsMissing()
throws Exception {
final String file = "FieldInitNoConstructor.java";
new PmdAssert(
file, Matchers.is(false),
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.NO_CON_INIT, file)
)
)
).validate();
}
/**
* PmdValidator can forbid field initialization when constructor exists.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFieldInitializationWhenConstructorExists()
throws Exception {
final String file = "FieldInitConstructor.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.NO_CON_INIT, file)
)
).validate();
}
/**
* PmdValidator can allow static field initialization when constructor
* exists.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsStaticFieldInitializationWhenConstructorExists()
throws Exception {
final String file = "StaticFieldInitConstructor.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.NO_CON_INIT, file)
)
)
).validate();
}
/**
* PmdValidator can forbid field initialization in several constructors.
* Only one constructor should do real work. Others - delegate to it.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFieldInitializationInSeveralConstructors()
throws Exception {
final String file = "FieldInitSeveralConstructors.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.MULT_CON_INIT, file)
)
).validate();
}
/**
* PmdValidator can allow field initialization in one constructor.
* Only one constructor should do real work. Others - delegate to it.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsFieldInitializationInOneConstructor()
throws Exception {
final String file = "FieldInitOneConstructor.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.MULT_CON_INIT, file)
)
)
).validate();
}
/**
* PmdValidator forbids unnecessary final modifier for methods.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsUnnecessaryFinalModifier()
throws Exception {
final String file = "UnnecessaryFinalModifier.java";
new PmdAssert(
file, Matchers.is(false),
Matchers.containsString("Unnecessary modifier 'final'")
).validate();
}
/**
* PmdValidator forbid useless parentheses.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsUselessParentheses()
throws Exception {
final String file = "UselessParentheses.java";
new PmdAssert(
file, Matchers.is(false),
Matchers.containsString("Useless parentheses")
).validate();
}
/**
* PmdValidator forbids code in constructor
* other than field initialization.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsCodeInConstructor()
throws Exception {
final String file = "CodeInConstructor.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.CODE_IN_CON, file)
)
).validate();
}
/**
* PmdValidator allows lambda in constructor.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsLambdaInConstructor()
throws Exception {
final String file = "LambdaInConstructor.java";
new PmdAssert(
file, new IsEqual<>(true),
new IsNot<>(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.CODE_IN_CON, file)
)
)
).validate();
}
/**
* PmdValidator forbids usage of Files.createFile in tests.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFilesCreateFileInTests() throws Exception {
new PmdAssert(
"FilesCreateFileTest.java",
Matchers.is(false),
Matchers.containsString(
PmdValidatorTest.FILES_CREATE_ERR
)
).validate();
}
/**
* PmdValidator allows usage of Files.createFile outside of tests.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsFilesCreateFileOutsideOfTests() throws Exception {
new PmdAssert(
"FilesCreateFileOther.java",
Matchers.is(true),
Matchers.not(
Matchers.containsString(
PmdValidatorTest.FILES_CREATE_ERR
)
)
).validate();
}
/**
* PmdValidator accepts calls to other constructors
* or call to super class constructor in constructors.
* @throws Exception If something wrong happens inside.
*/
@Test
public void acceptsCallToConstructorInConstructor()
throws Exception {
final String file = "CallToConstructorInConstructor.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.CODE_IN_CON, file)
)
)
).validate();
}
/**
* PmdValidator accepts calls to static fields
* in a static way.
* @throws Exception If something wrong happens inside.
*/
@Test
public void acceptsCallToStaticFieldsInStaticWay()
throws Exception {
final String file = "StaticAccessToStaticFields.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.allOf(
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.STATIC_ACCESS, file)
)
),
Matchers.not(
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.STATIC_VIA_THIS, file)
)
)
)
).validate();
}
/**
* PmdValidator forbids calls to static fields directly
* in a non static way.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsCallToStaticFieldsDirectly()
throws Exception {
final String file = "DirectAccessToStaticFields.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.STATIC_ACCESS, file)
)
).validate();
}
/**
* PmdValidator forbids calls to static fields
* in a non static way via instance reference.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsCallToStaticFieldsViaThis()
throws Exception {
final String file = "AccessToStaticFieldsViaThis.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.STATIC_VIA_THIS, file)
)
).validate();
}
/**
* PmdValidator forbids calls to static methods
* in a non static way via instance reference.
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsCallToStaticMethodsViaThis()
throws Exception {
final String file = "AccessToStaticMethodsViaThis.java";
new PmdAssert(
file, Matchers.is(false),
RegexMatchers.containsPattern(
String.format(PmdValidatorTest.STATIC_VIA_THIS, file)
)
).validate();
}
/**
* PmdValidator forbids non public clone methods (PMD rule
* rulesets/java/clone.xml/CloneMethodMustBePublic).
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsNonPublicCloneMethod() throws Exception {
new PmdAssert(
"CloneMethodMustBePublic.java",
Matchers.is(false),
Matchers.containsString(
String.format(
PmdValidatorTest.BRACKETS,
"CloneMethodMustBePublic"
)
)
).validate();
}
/**
* PmdValidator forbids clone methods with return type not matching class
* name (PMD rule
* rulesets/java/clone.xml/CloneMethodReturnTypeMustMatchClassName).
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsCloneMethodReturnTypeNotMatchingClassName()
throws Exception {
new PmdAssert(
"CloneMethodReturnTypeMustMatchClassName.java",
Matchers.is(false),
Matchers.containsString(
String.format(
PmdValidatorTest.BRACKETS,
"CloneMethodReturnTypeMustMatchClassName"
)
)
).validate();
}
/**
* PmdValidator forbids ternary operators that can be simplified (PMD rule
* rulesets/java/basic.xml/SimplifiedTernary).
* @throws Exception If something wrong happens inside.
*/
@Test
public void forbidsNonSimplifiedTernaryOperators()
throws Exception {
new PmdAssert(
"SimplifiedTernary.java",
Matchers.is(false),
Matchers.containsString(
String.format(
PmdValidatorTest.BRACKETS,
"SimplifiedTernary"
)
)
).validate();
}
/**
* PmdValidator can prohibit plain JUnit assertion in import block like
* import static org.junit.Assert.assert*
* import static junit.framework.Assert.assert*.
*
* Custom Rule {@link ProhibitPlainJunitAssertionsRule}
* @throws Exception If something wrong happens inside.
*/
@Test
public void prohibitsStaticImportsPlainAssertionsInTests()
throws Exception {
final String file = "PlainJUnitAssertionStaticImportBlock.java";
new PmdAssert(
file, Matchers.is(false),
Matchers.containsString(
PmdValidatorTest.PLAIN_ASSERTIONS
)
).validate();
}
/**
* PmdValidator can prohibit plain JUnit assertion in test methods like
* Assert.assertEquals.
*
* Custom Rule {@link ProhibitPlainJunitAssertionsRule}
* @throws Exception If something wrong happens inside.
*/
@Test
public void prohibitsPlainJunitAssertionsInTestMethods()
throws Exception {
final String file = "PlainJUnitAssertionTestMethod.java";
new PmdAssert(
file, Matchers.is(false),
Matchers.containsString(
PmdValidatorTest.PLAIN_ASSERTIONS
)
).validate();
}
/**
* PmdValidator can allow Assert.fail().
*
* Custom Rule {@link ProhibitPlainJunitAssertionsRule}
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsAssertFail()
throws Exception {
final String file = "AllowAssertFail.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.not(
Matchers.containsString(
PmdValidatorTest.PLAIN_ASSERTIONS
)
)
).validate();
}
/**
* PmdValidator can allow non-static, non-transient fields.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsNonTransientFields() throws Exception {
final String file = "AllowNonTransientFields.java";
new PmdAssert(
file, Matchers.is(true),
Matchers.not(
Matchers.containsString(
"Found non-transient, non-static member."
)
)
).validate();
}
/**
* PmdValidator can prohibit public static methods.
* @throws Exception If something wrong happens inside.
*/
@Test
public void prohibitsPublicStaticMethods() throws Exception {
new PmdAssert(
"StaticPublicMethod.java",
Matchers.is(false),
Matchers.containsString(PmdValidatorTest.STATIC_METHODS)
).validate();
}
/**
* PmdValidator can allow public static void main(String...args) method.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsPublicStaticMainMethod() throws Exception {
new PmdAssert(
"StaticPublicVoidMainMethod.java",
Matchers.is(true),
Matchers.not(
Matchers.containsString(PmdValidatorTest.STATIC_METHODS)
)
).validate();
}
/**
* PmdValidator can allow JUnit public static methods marked with:<br>
* BeforeClass annotation.<br>
* AfterClass annotation.<br>
* Parameterized.Parameters annotation.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsJunitFrameworkPublicStaticMethods() throws Exception {
new PmdAssert(
"JunitStaticPublicMethods.java",
Matchers.is(true),
Matchers.not(
Matchers.containsString(PmdValidatorTest.STATIC_METHODS)
)
).validate();
}
/**
* PmdValidator can allow duplicate literals in annotations.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowsDuplicateLiteralsInAnnotations() throws Exception {
new PmdAssert(
"AllowsDuplicateLiteralsInAnnotations.java",
Matchers.is(true),
Matchers.not(
Matchers.containsString("AvoidDuplicateLiterals")
)
).validate();
}
/**
* PmdValidator can allow only package private methods,
* annotated by @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest.
* @throws Exception If something wrong happens inside.
*/
@Test
public void testShouldBePackagePrivate() throws Exception {
new PmdAssert(
"TestShouldBePackagePrivate.java",
Matchers.is(false),
Matchers.containsString("JUnit5TestShouldBePackagePrivate")
).validate();
}
/**
* PmdValidator can allow only final JUnit3 test classes.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowJunitThirdTestClassToBeFinal() throws Exception {
new PmdAssert(
"Junit3TestClassShouldBeFinal.java",
Matchers.is(false),
Matchers.containsString("JUnitTestClassShouldBeFinal")
).validate();
}
/**
* PmdValidator can allow only final JUnit4 test classes.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowJunitFourthTestClassToBeFinal() throws Exception {
new PmdAssert(
"Junit4TestClassShouldBeFinal.java",
Matchers.is(false),
Matchers.containsString("JUnitTestClassShouldBeFinal")
).validate();
}
/**
* PmdValidator can allow only final JUnit5 test classes.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowJunitFifthTestClassToBeFinal() throws Exception {
new PmdAssert(
"Junit5TestClassShouldBeFinal.java",
Matchers.is(false),
Matchers.containsString("JUnitTestClassShouldBeFinal")
).validate();
}
/**
* PmdValidator can allow only final Junit test classes.
* @throws Exception If something wrong happens inside.
*/
@Test
public void allowJunitTestClassToBeFinal() throws Exception {
new PmdAssert(
"JunitTestClassIsFinal.java",
Matchers.is(true),
Matchers.not(
Matchers.containsString("JUnitTestClassShouldBeFinal")
)
).validate();
}
}