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