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       * File to validate.
24       */
25      private final String file;
26  
27      /**
28       * Expected build status, true means success.
29       */
30      private final Matcher<Boolean> result;
31  
32      /**
33       * Matcher that needs to match.
34       */
35      private final Matcher<String> matcher;
36  
37      /**
38       * Constructor.
39       *
40       * @param file File to validate.
41       * @param result Expected build status.
42       * @param matcher Matcher that needs to match.
43       */
44      PmdAssert(
45          final String file,
46          final Matcher<Boolean> result,
47          final Matcher<String> matcher
48      ) {
49          this.file = file;
50          this.result = result;
51          this.matcher = matcher;
52      }
53  
54      /**
55       * Validates given file against PMD.
56       *
57       * @throws Exception In case of error.
58       */
59      public void validate() throws Exception {
60          final Environment.Mock mock = new Environment.Mock();
61          final String name = String.format("src/main/java/foo/%s", this.file);
62          final Environment env = mock.withFile(
63              name,
64              new TextOf(
65                  this.getClass().getResourceAsStream(this.file)
66              ).asString()
67          );
68          final Collection<Violation> violations = new PmdValidator(env).validate(
69              Collections.singletonList(new File(env.basedir(), name))
70          );
71          MatcherAssert.assertThat(violations.isEmpty(), this.result);
72          final StringBuilder builder = new StringBuilder();
73          for (final Violation violation : violations) {
74              builder.append(
75                  String.format(
76                      "PMD: %s[%s]: %s (%s)\n",
77                      this.file,
78                      violation.lines(),
79                      violation.message(),
80                      violation.name()
81                  )
82              );
83          }
84          MatcherAssert.assertThat(builder.toString(), this.matcher);
85      }
86  }