1
2
3
4
5 package com.qulice.checkstyle;
6
7 import com.qulice.spi.Environment;
8 import com.qulice.spi.Violation;
9 import java.io.File;
10 import java.io.IOException;
11 import java.util.Collection;
12 import org.cactoos.io.ResourceOf;
13 import org.cactoos.text.FormattedText;
14 import org.cactoos.text.IoCheckedText;
15 import org.cactoos.text.TextOf;
16 import org.hamcrest.MatcherAssert;
17 import org.hamcrest.Matchers;
18 import org.junit.jupiter.api.Assertions;
19 import org.junit.jupiter.api.Test;
20
21
22
23
24
25
26 final class ConstantUsageCheckTest {
27
28 @Test
29 void acceptsConstantUsedInMethodAnnotation() throws Exception {
30 Assertions.assertDoesNotThrow(
31 () -> this.runValidation("AnnotationConstant.java", true)
32 );
33 }
34
35 @Test
36 void acceptsConstantUsedInFieldAndClassAnnotations() throws Exception {
37 Assertions.assertDoesNotThrow(
38 () -> this.runValidation("AnnotationConstantField.java", true)
39 );
40 }
41
42 @Test
43 void acceptsConstantUsedBeforeItsDeclaration() throws Exception {
44 final String file = "ConstantUsedBeforeDeclaration.java";
45 MatcherAssert.assertThat(
46 "private constant used by earlier-declared constants must not be flagged as unused",
47 this.runValidation(file, false),
48 Matchers.not(
49 Matchers.hasItem(
50 new ViolationMatcher(
51 "Private constant \"OP_ZERO\" is not used", file
52 )
53 )
54 )
55 );
56 }
57
58 private Collection<Violation> runValidation(final String file,
59 final boolean passes) throws IOException {
60 final Environment.Mock mock = new Environment.Mock();
61 final Environment env = mock.withParam(
62 "license",
63 String.format(
64 "file:%s",
65 new License().savePackageInfo(
66 new File(mock.basedir(), "src/main/java/foo")
67 ).withLines("Hello.")
68 .withEol(String.valueOf('\n')).file()
69 )
70 ).withFile(
71 String.format("src/main/java/foo/%s", file),
72 new IoCheckedText(
73 new TextOf(
74 new ResourceOf(
75 new FormattedText("com/qulice/checkstyle/%s", file)
76 )
77 )
78 ).asString()
79 );
80 final Collection<Violation> results =
81 new CheckstyleValidator(env).validate(env.files(file));
82 MatcherAssert.assertThat(
83 "validation result should match expected state",
84 results.isEmpty(),
85 Matchers.is(passes)
86 );
87 return results;
88 }
89 }