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.Collections;
11  import java.util.stream.Collectors;
12  import org.cactoos.text.TextOf;
13  import org.hamcrest.MatcherAssert;
14  import org.hamcrest.Matchers;
15  import org.junit.jupiter.api.Test;
16  
17  /**
18   * Test case for {@link com.qulice.pmd.rules.ProhibitFormatInLoggerRule}.
19   * @since 0.26.0
20   */
21  final class ProhibitFormatInLoggerRuleTest {
22  
23      @Test
24      void detectsStringFormatInsideLoggerCall() throws Exception {
25          final String file = "StringFormatInsideLogger.java";
26          final Environment.Mock mock = new Environment.Mock();
27          final String name = String.format("src/main/java/foo/%s", file);
28          final Environment env = mock.withFile(
29              name,
30              new TextOf(
31                  this.getClass().getResourceAsStream(file)
32              ).asString()
33          );
34          MatcherAssert.assertThat(
35              "ProhibitFormatInLogger should fire when String.format is the message argument of a Logger call",
36              new PmdValidator(env).validate(
37                  Collections.singletonList(new File(env.basedir(), name))
38              ).stream().map(Violation::name).collect(Collectors.toList()),
39              Matchers.hasItem("ProhibitFormatInLoggerRule")
40          );
41      }
42  
43      @Test
44      void doesNotFireOnDirectLoggerCall() throws Exception {
45          final String file = "PlainLoggerCalls.java";
46          final Environment.Mock mock = new Environment.Mock();
47          final String name = String.format("src/main/java/foo/%s", file);
48          final Environment env = mock.withFile(
49              name,
50              new TextOf(
51                  this.getClass().getResourceAsStream(file)
52              ).asString()
53          );
54          MatcherAssert.assertThat(
55              "ProhibitFormatInLogger should not fire when Logger gets a plain format string and arguments",
56              new PmdValidator(env).validate(
57                  Collections.singletonList(new File(env.basedir(), name))
58              ).stream().map(Violation::name).collect(Collectors.toList()),
59              Matchers.not(Matchers.hasItem("ProhibitFormatInLoggerRule"))
60          );
61      }
62  }