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