View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.qulice.spi.Violation;
8   import org.hamcrest.Description;
9   import org.hamcrest.TypeSafeMatcher;
10  
11  /**
12   * Matcher for {@link Violation} produced by {@link CheckstyleValidator}
13   * in unit tests. Matches by substring of the message, suffix of the file
14   * path and, optionally, exact line number and check name.
15   * @since 0.1
16   */
17  final class ViolationMatcher extends TypeSafeMatcher<Violation> {
18  
19      /**
20       * Message to check.
21       */
22      private final String message;
23  
24      /**
25       * File to check.
26       */
27      private final String file;
28  
29      /**
30       * Expected line.
31       */
32      private final String line;
33  
34      /**
35       * Check name.
36       */
37      private final String check;
38  
39      /**
40       * Constructor.
41       * @param message Message to check
42       * @param file File to check
43       */
44      ViolationMatcher(final String message, final String file) {
45          this(message, file, "", "");
46      }
47  
48      /**
49       * Constructor.
50       * @param message Message to check
51       * @param file File to check
52       * @param line Line to check
53       * @param check Check name
54       * @checkstyle ParameterNumber (3 lines)
55       */
56      ViolationMatcher(final String message, final String file,
57          final String line, final String check) {
58          super();
59          this.message = message;
60          this.file = file;
61          this.line = line;
62          this.check = check;
63      }
64  
65      @Override
66      public boolean matchesSafely(final Violation item) {
67          return item.message().contains(this.message)
68              && item.file().endsWith(this.file)
69              && this.lineMatches(item)
70              && this.checkMatches(item);
71      }
72  
73      @Override
74      public void describeTo(final Description description) {
75          description.appendText("doesn't match");
76      }
77  
78      /**
79       * Check name matches.
80       * @param item Item to check
81       * @return True if check name matches
82       */
83      private boolean checkMatches(final Violation item) {
84          return this.check.isEmpty()
85              || !this.check.isEmpty() && item.name().equals(this.check);
86      }
87  
88      /**
89       * Check that given line matches.
90       * @param item Item to check
91       * @return True if line matches
92       */
93      private boolean lineMatches(final Violation item) {
94          return this.line.isEmpty()
95              || !this.line.isEmpty() && item.lines().equals(this.line);
96      }
97  }