View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.pmd;
6   
7   import com.qulice.spi.Environment;
8   import com.qulice.spi.Violation;
9   import java.io.File;
10  import java.util.Collection;
11  import java.util.Collections;
12  import org.cactoos.text.TextOf;
13  import org.hamcrest.Matcher;
14  import org.hamcrest.MatcherAssert;
15  
16  /**
17   * PMD Validator assertions.
18   *
19   * @since 0.16
20   */
21  final class PmdAssert {
22  
23      /**
24       * File to validate.
25       */
26      private final String file;
27  
28      /**
29       * Expected build status, true means success.
30       */
31      private final Matcher<Boolean> result;
32  
33      /**
34       * Matcher that needs to match.
35       */
36      private final Matcher<String> matcher;
37  
38      /**
39       * Constructor.
40       *
41       * @param file File to validate
42       * @param result Expected build status
43       * @param matcher Matcher that needs to match
44       */
45      PmdAssert(
46          final String file,
47          final Matcher<Boolean> result,
48          final Matcher<String> matcher
49      ) {
50          this.file = file;
51          this.result = result;
52          this.matcher = matcher;
53      }
54  
55      /**
56       * Validates given file against PMD.
57       *
58       * @throws Exception In case of error.
59       */
60      void assertOk() throws Exception {
61          final Environment.Mock mock = new Environment.Mock();
62          final String name = String.format("src/main/java/foo/%s", this.file);
63          final Environment env = mock.withFile(
64              name,
65              new TextOf(
66                  this.getClass().getResourceAsStream(this.file)
67              ).asString()
68          );
69          final Collection<Violation> violations = new PmdValidator(env).validate(
70              Collections.singletonList(new File(env.basedir(), name))
71          );
72          MatcherAssert.assertThat(violations.isEmpty(), this.result);
73          final StringBuilder builder = new StringBuilder();
74          for (final Violation violation : violations) {
75              builder.append(
76                  String.format(
77                      "PMD: %s[%s]: %s (%s)%n",
78                      this.file,
79                      violation.lines(),
80                      violation.message(),
81                      violation.name()
82                  )
83              );
84          }
85          MatcherAssert.assertThat(builder.toString(), this.matcher);
86      }
87  }