Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alban-auzeill committed May 30, 2024
1 parent 8d2de9a commit 092c3c7
Show file tree
Hide file tree
Showing 5 changed files with 198 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ private void warnAboutNonFixedSonarPluginVersion() {
MavenProject project = session.getTopLevelProject();
List<String> goals = session.getGoals();
Log log = getLog();
if (Arrays.asList(effectivePluginVersion, groupId, artifactId, plugin, log, project, goals).contains(null)) {
boolean anyRequiredArgumentsIsNull = Arrays.asList(effectivePluginVersion, groupId, artifactId, plugin, log, project, goals).contains(null);
if (anyRequiredArgumentsIsNull) {
return;
}
String invalidPluginVersion = null;
Expand Down Expand Up @@ -209,4 +210,8 @@ private boolean isSkip(Map<String, String> properties) {
MavenSession getSession() {
return session;
}

MojoExecution getMojoExecution() {
return mojoExecution;
}
}
142 changes: 114 additions & 28 deletions src/test/java/org/sonarsource/scanner/maven/SonarQubeMojoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,48 +23,47 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.apache.maven.execution.ProjectDependencyGraph;
import org.apache.maven.graph.GraphBuilder;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginManagement;
import org.apache.maven.model.building.Result;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.testing.MojoRule;
import org.apache.maven.project.MavenProject;
import org.assertj.core.api.Condition;
import org.assertj.core.data.MapEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonarsource.scanner.maven.TimestampLoggerTest.TestLog;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SonarQubeMojoTest {

private static final String DEFAULT_GOAL = "org.sonarsource.scanner.maven:sonar-maven-plugin:sonar";

@Rule
public MojoRule mojoRule = new MojoRule();

private Log mockedLogger;
private TestLog logger = new TestLog(TestLog.LogLevel.WARN);

private SonarQubeMojo getMojo(File baseDir) throws Exception {
return (SonarQubeMojo) mojoRule.lookupConfiguredMojo(baseDir, "sonar");
}

@Before
public void setUpMocks() {
mockedLogger = mock(Log.class);
}

@Test
public void executeMojo() throws Exception {
executeProject("sample-project");
Expand All @@ -78,7 +77,7 @@ public void executeMojo() throws Exception {
public void should_skip() throws Exception {
File propsFile = new File("target/dump.properties");
propsFile.delete();
executeProject("sample-project", "sonar.scanner.skip", "true");
executeProject("sample-project", DEFAULT_GOAL, "sonar.scanner.skip", "true");
assertThat(propsFile).doesNotExist();
}

Expand Down Expand Up @@ -111,6 +110,7 @@ public void shouldExportOverridenWarWebSource() throws Exception {
public void project_with_java_files_not_in_src_should_not_be_collected() throws Exception {
File baseDir = executeProject(
"project-with-java-files-not-in-src",
DEFAULT_GOAL,
"sonar.maven.scanAll", "true");
Set<String> actualListOfSources = extractSonarSources("target/dump.properties", baseDir.toPath());
assertThat(actualListOfSources).containsExactlyInAnyOrder(
Expand All @@ -121,6 +121,7 @@ public void project_with_java_files_not_in_src_should_not_be_collected() throws
public void project_with_java_files_not_in_src_should_be_collected_when_user_define_binaries_and_libraries() throws Exception {
File baseDir = executeProject(
"project-with-java-files-not-in-src",
DEFAULT_GOAL,
"sonar.maven.scanAll", "true",
"sonar.java.binaries", "target/classes",
"sonar.java.libraries", "target/lib/logger.jar");
Expand All @@ -133,6 +134,7 @@ public void project_with_java_files_not_in_src_should_be_collected_when_user_def
public void project_with_java_files_not_in_src_should_not_be_collected_when_user_define_only_binaries() throws Exception {
File baseDir = executeProject(
"project-with-java-files-not-in-src",
DEFAULT_GOAL,
"sonar.maven.scanAll", "true",
"sonar.java.binaries", "target/classes");
Set<String> actualListOfSources = extractSonarSources("target/dump.properties", baseDir.toPath());
Expand All @@ -144,6 +146,7 @@ public void project_with_java_files_not_in_src_should_not_be_collected_when_user
public void project_with_java_files_not_in_src_should_not_be_collected_when_user_define_only_libraries() throws Exception {
File baseDir = executeProject(
"project-with-java-files-not-in-src",
DEFAULT_GOAL,
"sonar.maven.scanAll", "true",
"sonar.java.libraries", "target/lib/logger.jar");
Set<String> actualListOfSources = extractSonarSources("target/dump.properties", baseDir.toPath());
Expand All @@ -169,55 +172,104 @@ public void shouldExportSurefireCustomReportsPath() throws Exception {
}

@Test
public void reuse_findbugs_exclusions_from_reporting() throws IOException, Exception {
public void reuse_findbugs_exclusions_from_reporting() throws Exception {
File baseDir = executeProject("project-with-findbugs-reporting");
assertPropsContains(entry("sonar.findbugs.excludeFilters", new File(baseDir, "findbugs-exclude.xml").getAbsolutePath()));
}

@Test
public void exclude_report_paths_from_scanAll() throws Exception {
File projectBarDir = executeProject("project-with-external-reports", "sonar.maven.scanAll", "true");
File projectBarDir = executeProject("project-with-external-reports", DEFAULT_GOAL, "sonar.maven.scanAll", "true");
Set<String> actualListOfSources = extractSonarSources("target/dump.properties", projectBarDir.toPath());
assertThat(actualListOfSources).containsExactlyInAnyOrder("/other.xml", "/pom.xml");
}

@Test
public void reuse_findbugs_exclusions_from_plugin() throws IOException, Exception {
public void reuse_findbugs_exclusions_from_plugin() throws Exception {
File baseDir = executeProject("project-with-findbugs-build");
assertPropsContains(entry("sonar.findbugs.excludeFilters", new File(baseDir, "findbugs-exclude.xml").getAbsolutePath()));
}

@Test
public void reuse_findbugs_exclusions_from_plugin_management() throws IOException, Exception {
public void reuse_findbugs_exclusions_from_plugin_management() throws Exception {
File baseDir = executeProject("project-with-findbugs-plugin-management");
assertPropsContains(entry("sonar.findbugs.excludeFilters", new File(baseDir, "findbugs-exclude.xml").getAbsolutePath()));
}

@Test
public void sonar_plugin_without_fix_version_should_display_a_warning() throws IOException, Exception {
TestLog testLog = new TestLog(TestLog.LogLevel.WARN);
executeProject("sample-project", Arrays.asList("sonar:sonar"), testLog);
//assertThat(testLog.logs).containsExactly("dc");
public void sonar_maven_plugin_version_not_set_should_display_a_warning() throws Exception {
executeProject("sample-project", "sonar:sonar");
String expected = "Using an unspecified version instead of a fixed plugin version may introduce breaking analysis changes at an unwanted time. " +
"It is highly recommended to use a fixed version," +
" e.g. 'org.sonarsource.scanner.maven:sonar-maven-plugin:";
assertThat(logger.logs).areAtLeastOne(new Condition<>(log -> log.contains(expected), "Missing: " + expected));
}

@Test
public void sonar_maven_plugin_version_LATEST_in_goal_should_display_a_warning() throws Exception {
executeProject("sample-project", "sonar:LATEST:sonar");
String expected = "Using LATEST instead of a fixed plugin version may introduce breaking analysis changes at an unwanted time. " +
"It is highly recommended to use a fixed version," +
" e.g. 'org.sonarsource.scanner.maven:sonar-maven-plugin:";
assertThat(logger.logs).areAtLeastOne(new Condition<>(log -> log.contains(expected), "Missing: " + expected));
}

@Test
public void sonar_maven_plugin_version_RELEASE_in_goal_should_display_a_warning() throws Exception {
executeProject("sample-project", "org.sonarsource.scanner.maven:sonar-maven-plugin:RELEASE:sonar");
String expected = "Using RELEASE instead of a fixed plugin version may introduce breaking analysis changes at an unwanted time. " +
"It is highly recommended to use a fixed version," +
" e.g. 'org.sonarsource.scanner.maven:sonar-maven-plugin:";
assertThat(logger.logs).areAtLeastOne(new Condition<>(log -> log.contains(expected), "Missing: " + expected));
}

@Test
public void sonar_maven_plugin_version_set_in_goal_should_not_display_a_warning() throws Exception {
executeProject("sample-project", "org.sonarsource.scanner.maven:sonar-maven-plugin:1.2.3.4:sonar");
logger.removeLogsContaining("Failed to collect configuration from the maven-compiler-plugin");
assertThat(logger.warnings()).isEmpty();
}

@Test
public void sonar_maven_plugin_version_set_in_sonar_sonar_goal_should_not_display_a_warning() throws Exception {
executeProject("sample-project", "sonar:1.2.3.4:sonar");
logger.removeLogsContaining("Failed to collect configuration from the maven-compiler-plugin");
assertThat(logger.warnings()).isEmpty();
}

@Test
public void sonar_maven_plugin_version_set_in_plugin_management_should_not_display_a_warning() throws Exception {
executeProject("project-with-sonar-plugin-management-configuration", "org.sonarsource.scanner.maven:sonar-maven-plugin:sonar");
logger.removeLogsContaining("Failed to collect configuration from the maven-compiler-plugin");
assertThat(logger.warnings()).isEmpty();
}

@Test
public void sonar_maven_plugin_version_set_in_build_plugins_should_not_display_a_warning() throws Exception {
executeProject("project-with-sonar-plugin-configuration", "org.sonarsource.scanner.maven:sonar-maven-plugin:sonar");
logger.removeLogsContaining("Failed to collect configuration from the maven-compiler-plugin");
assertThat(logger.warnings()).isEmpty();
}

@Test
public void verbose() throws Exception {
when(mockedLogger.isDebugEnabled()).thenReturn(true);
logger.setLogLevel(TestLog.LogLevel.DEBUG);
executeProject("project-with-findbugs-reporting");
verify(mockedLogger, atLeastOnce()).isDebugEnabled();
assertThat(readProps("target/dump.properties")).contains((entry("sonar.verbose", "true")));
}

private File executeProject(String projectName, String... properties) throws Exception {
return executeProject(projectName, Collections.singletonList("sonar:sonar"), mockedLogger, properties);
private File executeProject(String projectName) throws Exception {
return executeProject(projectName, DEFAULT_GOAL);
}

private File executeProject(String projectName, List<String> goals, Log logger, String... properties) throws Exception {
private File executeProject(String projectName, String goal, String... properties) throws Exception {
File baseDir = new File("src/test/projects/" + projectName).getAbsoluteFile();
SonarQubeMojo mojo = getMojo(baseDir);
mojo.getSession().getRequest().setGoals(goals);
mojo.getSession().getRequest().setGoals(Collections.singletonList(goal));
mojo.getSession().getProjects().get(0).setExecutionRoot(true);
mojo.getSession().setAllProjects(mojo.getSession().getProjects());
PluginDescriptor pluginDescriptor = mojo.getMojoExecution().getMojoDescriptor().getPluginDescriptor();
pluginDescriptor.setPlugin(createSonarPluginFrom(pluginDescriptor, goal, mojo.getSession().getTopLevelProject()));

Result<? extends ProjectDependencyGraph> result = mojoRule.lookup(GraphBuilder.class).build(mojo.getSession());
mojo.getSession().setProjectDependencyGraph(result.get()); // done by maven in a normal execution
Expand All @@ -238,8 +290,42 @@ private File executeProject(String projectName, List<String> goals, Log logger,
return baseDir;
}

private Plugin createSonarPluginFrom(PluginDescriptor pluginDescriptor, String goal, MavenProject project) {
String version = null;
Pattern versionPattern = Pattern.compile("(?:" +
"sonar|" +
"org\\.codehaus\\.mojo:sonar-maven-plugin|" +
"org\\.sonarsource\\.scanner\\.maven:sonar-maven-plugin" +
"):([^:]+):sonar");
Matcher matcher = versionPattern.matcher(goal);
if (matcher.matches()) {
version = matcher.group(1);
}
if (version == null) {
List<Plugin> plugins = new ArrayList<>(project.getBuildPlugins());
PluginManagement pluginManagement = project.getPluginManagement();
if (pluginManagement != null) {
plugins.addAll(pluginManagement.getPlugins());
}
for (Plugin plugin : plugins) {
String pluginGroupId = plugin.getGroupId();
if ((pluginGroupId == null || pluginGroupId.equals(pluginDescriptor.getGroupId())) &&
pluginDescriptor.getArtifactId().equals(plugin.getArtifactId()) &&
plugin.getVersion() != null){
version = plugin.getVersion();
break;
}
}
}
Plugin plugin = new Plugin();
plugin.setGroupId(pluginDescriptor.getGroupId());
plugin.setArtifactId(pluginDescriptor.getArtifactId());
plugin.setVersion(version);
return plugin;
}

@SafeVarargs
private final void assertPropsContains(MapEntry<String, String>... entries) throws IOException {
private void assertPropsContains(MapEntry<String, String>... entries) throws IOException {
assertThat(readProps("target/dump.properties")).contains(entries);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.maven.plugin.logging.Log;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
Expand Down Expand Up @@ -109,13 +110,17 @@ public enum LogLevel {
ERROR,
}

public final LogLevel logLevel;
public LogLevel logLevel;
public final List<String> logs = new ArrayList<>();

public TestLog(LogLevel logLevel) {
this.logLevel = logLevel;
}

public void setLogLevel(LogLevel logLevel) {
this.logLevel = logLevel;
}

@Override
public boolean isDebugEnabled() {
return logLevel == LogLevel.DEBUG;
Expand Down Expand Up @@ -166,6 +171,10 @@ public void warn(CharSequence content) {
logs.add("[WARN] " + content);
}

public List<String> warnings() {
return logs.stream().filter(log -> log.startsWith("[WARN] ")).collect(Collectors.toList());
}

@Override
public void warn(CharSequence content, Throwable error) {
warn(content);
Expand Down Expand Up @@ -195,5 +204,9 @@ public void error(CharSequence content, Throwable error) {
public void error(Throwable error) {
error(error.getMessage());
}

public void removeLogsContaining(String text) {
logs.removeIf(log -> log.contains(text));
}
}
}
25 changes: 25 additions & 0 deletions src/test/projects/project-with-sonar-plugin-configuration/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.codehaus.sonar</groupId>
<artifactId>sample-project</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Test project</name>

<properties>
<sonar.scanner.dumpToFile>target/dump.properties</sonar.scanner.dumpToFile>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>1.2.3.4</version>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.codehaus.sonar</groupId>
<artifactId>sample-project</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Test project</name>

<properties>
<sonar.scanner.dumpToFile>target/dump.properties</sonar.scanner.dumpToFile>
</properties>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>unknow-group-id</groupId>
<artifactId>sonar-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>unknow-artifact-id</artifactId>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>1.2.3.4</version>
</plugin>
</plugins>
</pluginManagement>
</build>

</project>

0 comments on commit 092c3c7

Please sign in to comment.