@Test public void test() throws Exception { assertTrue( "SonarQube 5.1 is the minimum version to generate the issues report, change your orchestrator.properties", orchestrator.getConfiguration().getSonarVersion().isGreaterThanOrEquals("5.1")); File litsDifferencesFile = FileLocation.of("target/differences").getFile(); SonarRunner build = SonarRunner.create(FileLocation.of("../sources/src").getFile()) .setProjectKey("project") .setProjectName("project") .setProjectVersion("1") .setLanguage("js") .setSourceDirs("./") .setSourceEncoding("utf-8") .setProfile("rules") .setProperty("sonar.analysis.mode", "preview") .setProperty("sonar.issuesReport.html.enable", "true") .setProperty( "dump.old", FileLocation.of("src/test/expected").getFile().getAbsolutePath()) .setProperty("dump.new", FileLocation.of("target/actual").getFile().getAbsolutePath()) .setProperty("lits.differences", litsDifferencesFile.getAbsolutePath()) .setProperty("sonar.cpd.skip", "true") .setEnvironmentVariable("SONAR_RUNNER_OPTS", "-Xmx1024m"); orchestrator.executeBuild(build); assertThat(Files.toString(litsDifferencesFile, StandardCharsets.UTF_8)).isEmpty(); }
// SONAR-4602 @Test public void no_issues_mode_cache_after_profile_change() throws Exception { restoreProfile("one-issue-per-line-empty.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator .getServer() .associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); // First run (publish mode) SonarRunner runner = configureRunner("shared/xoo-sample"); orchestrator.executeBuild(runner); // First issues mode runner = configureRunnerIssues("shared/xoo-sample"); BuildResult result = orchestrator.executeBuild(runner); // No new issues assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(0); // Modification of QP should invalidate cache restoreProfile("/one-issue-per-line.xml"); // Second issues mode runner = configureRunnerIssues("shared/xoo-sample", "sonar.report.export.path", "sonar-report.json"); result = orchestrator.executeBuild(runner); // As many new issue as lines assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(17); }
@BeforeClass public static void scanStruts() { orchestrator.resetData(); orchestrator.executeBuild(SonarRunner.create(projectDir("shared/xoo-multi-modules-sample"))); createUser("user-measure-filters", "User Measure Filters"); }
private String exportProfile(String profileName) { String response; if (AndroidTestSuite.sonarqube_version_is_after_5_2()) { response = orchestrator .getServer() .adminWsClient() .get( "api/qualityprofiles/export", "language", "java", "name", profileName, "exporterKey", "android-lint"); } else { response = orchestrator .getServer() .adminWsClient() .get( "profiles/export", "language", "java", "name", profileName, "format", "android-lint"); } return response; }
@BeforeClass public static void setUp() { wsClient = newAdminWsClient(ORCHESTRATOR); ORCHESTRATOR.resetData(); ORCHESTRATOR.executeBuild( SonarScanner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.links.homepage", "http://example.com")); }
@Override public void execute(Dsl.Context context) { Orchestrator orchestrator = context.getOrchestrator(); Preconditions.checkState( orchestrator != null, "The command 'start server' has not been executed"); Sonar client = orchestrator.getServer().getWsClient(); verifyMeasures(client); }
@Before public void setUpProject() throws IOException { orchestrator.resetData(); orchestrator .getServer() .restoreProfile(FileLocation.ofClasspath("/duplication/xoo-duplication-profile.xml")); FileUtils.copyDirectory(ItUtils.projectDir(PROJECT_DIR), temp.getRoot()); projectDir = temp.getRoot(); }
@BeforeClass public static void analyzeProject() { orchestrator.resetData(); MavenBuild build = MavenBuild.create(TestUtils.projectPom("java-complexity")) .setCleanSonarGoals() .setProperty("sonar.dynamicAnalysis", "false") .setProperty("sonar.profile", "java-complexity"); orchestrator.executeBuild(build); }
// SONAR-6522 @Test public void load_user_name_in_json_report() throws Exception { restoreProfile("one-issue-per-line.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator .getServer() .associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); // First run (publish mode) SonarRunner runner = configureRunner("shared/xoo-sample"); orchestrator.executeBuild(runner); SonarClient client = orchestrator.getServer().adminWsClient(); Issues issues = client.issueClient().find(IssueQuery.create()); Issue issue = issues.list().get(0); UserParameters creationParameters = UserParameters.create() .login("julien") .name("Julien H") .password("password") .passwordConfirmation("password"); client.userClient().create(creationParameters); // Assign issue client.issueClient().assign(issue.key(), "julien"); // Issues runner = configureRunnerIssues("shared/xoo-sample"); BuildResult result = orchestrator.executeBuild(runner); JSONObject obj = ItUtils.getJSONReport(result); Map<String, String> userNameByLogin = Maps.newHashMap(); final JSONArray users = (JSONArray) obj.get("users"); if (users != null) { for (Object user : users) { String login = ObjectUtils.toString(((JSONObject) user).get("login")); String name = ObjectUtils.toString(((JSONObject) user).get("name")); userNameByLogin.put(login, name); } } assertThat(userNameByLogin.get("julien")).isEqualTo("Julien H"); for (Object issueJson : (JSONArray) obj.get("issues")) { JSONObject jsonObject = (JSONObject) issueJson; if (issue.key().equals(jsonObject.get("key"))) { assertThat(jsonObject.get("assignee")).isEqualTo("julien"); return; } } fail("Issue not found"); }
@Test public void issues_analysis_on_new_project() throws IOException { restoreProfile("one-issue-per-line.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator .getServer() .associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); SonarRunner runner = configureRunnerIssues("shared/xoo-sample", "sonar.verbose", "true"); BuildResult result = orchestrator.executeBuild(runner); assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(17); }
/** SONAR-6787 */ @Test public void ensure_differential_period_4_and_5_defined_at_project_level_is_taken_into_account() throws Exception { orchestrator.getServer().provisionProject(PROJECT_KEY, PROJECT_KEY); setServerProperty(orchestrator, PROJECT_KEY, "sonar.timemachine.period4", "30"); setServerProperty(orchestrator, PROJECT_KEY, "sonar.timemachine.period5", "previous_analysis"); // Execute an analysis in the past to have a past snapshot without any issues orchestrator.getServer().associateProjectToQualityProfile(PROJECT_KEY, "xoo", "empty"); orchestrator.executeBuild( SonarRunner.create(projectDir("shared/xoo-sample")) .setProperty("sonar.projectDate", formatDate(addDays(new Date(), -60)))); // Second analysis -> issues will be created orchestrator .getServer() .restoreProfile(FileLocation.ofClasspath("/measureHistory/one-issue-per-line-profile.xml")); orchestrator .getServer() .associateProjectToQualityProfile(PROJECT_KEY, "xoo", "one-issue-per-line"); orchestrator.executeBuild(SonarRunner.create(projectDir("shared/xoo-sample"))); // New technical debt only comes from new issues Resource newTechnicalDebt = orchestrator .getServer() .getWsClient() .find( ResourceQuery.createForMetrics( "sample:src/main/xoo/sample/Sample.xoo", "new_technical_debt") .setIncludeTrends(true)); List<Measure> measures = newTechnicalDebt.getMeasures(); assertThat(measures.get(0).getVariation4()).isEqualTo(17); assertThat(measures.get(0).getVariation5()).isEqualTo(17); // Third analysis, with exactly the same profile -> no new issues so no new technical debt orchestrator .getServer() .associateProjectToQualityProfile(PROJECT_KEY, "xoo", "one-issue-per-line"); orchestrator.executeBuild(SonarRunner.create(projectDir("shared/xoo-sample"))); newTechnicalDebt = orchestrator .getServer() .getWsClient() .find( ResourceQuery.createForMetrics( "sample:src/main/xoo/sample/Sample.xoo", "new_technical_debt") .setIncludeTrends(true)); // No variation => measure is purged assertThat(newTechnicalDebt).isNull(); }
@Test public void concurrent_issue_mode_on_existing_project() throws Exception { restoreProfile("one-issue-per-line.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator .getServer() .associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); SonarRunner runner = configureRunner("shared/xoo-sample"); orchestrator.executeBuild(runner); runConcurrentIssues(); }
@Test public void non_associated_mode() throws IOException { restoreProfile("one-issue-per-line.xml"); setDefaultQualityProfile("xoo", "one-issue-per-line"); SonarRunner runner = configureRunnerIssues("shared/xoo-sample-non-associated"); BuildResult result = orchestrator.executeBuild(runner); assertThat(result.getLogs()).contains("Local analysis"); assertThat(result.getLogs()).contains("Cache not found, synchronizing data"); assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(17); result = orchestrator.executeBuild(runner); assertThat(ItUtils.countIssuesInJsonReport(result, true)).isEqualTo(17); assertThat(result.getLogs()).contains("Found cache"); }
@Test public void invalid_incremental_mode() throws IOException { restoreProfile("one-issue-per-line.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator .getServer() .associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); SonarRunner runner = configureRunner("shared/xoo-sample"); runner.setProperty("sonar.analysis.mode", "incremental"); thrown.expect(BuildFailureException.class); BuildResult res = orchestrator.executeBuild(runner); assertThat(res.getLogs()) .contains("Invalid analysis mode: incremental. This mode was removed in SonarQube 5.2"); }
@Test // SONARJS-301 public void print_log_for_not_found_resource() throws InterruptedException { SonarRunner build = Tests.createSonarRunnerBuild() .setProjectDir(TestUtils.projectDir("lcov")) .setProjectKey("project") .setProjectName("project") .setProjectVersion("1.0") .setSourceDirs(".") .setProperty( "sonar.javascript.lcov.reportPath", TestUtils.file("projects/lcov/coverage-wrong-file-name.lcov").getAbsolutePath()) .setDebugLogs(true); BuildResult result = orchestrator.executeBuild(build); // Check that a log is printed String logs = result.getLogs(); assertThat(Pattern.compile("Analysing .*coverage-wrong-file-name\\.lcov").matcher(logs).find()) .isTrue(); assertThat( Pattern.compile("Default value of zero will be saved for file: .*file\\.js") .matcher(logs) .find()) .isTrue(); assertThat( Pattern.compile( "INFO.*Could not resolve 1 file paths in coverage-wrong-file-name\\.lcov, " + "first unresolved path: \\./wrong/fileName\\.js") .matcher(logs) .find()) .isTrue(); }
private void setDefaultQualityProfile(String languageKey, String profileName) { orchestrator .getServer() .adminWsClient() .post( "api/qualityprofiles/set_default", "language", languageKey, "profileName", profileName); }
@Test public void should_use_new_java_binaries_property() { SonarScanner scanner = ditProjectSonarScanner(); scanner.setProperty("sonar.java.binaries", "target/classes"); ORCHESTRATOR.executeBuild(scanner); assertThat(getNumberOfViolations(PROJECT_KEY_DIT)).isEqualTo(1); }
static String getProperty(String key) { return orchestrator .getServer() .getAdminWsClient() .find(new PropertyQuery().setKey(key)) .getValue(); }
@Test public void relative_path_and_wildcard_for_binaries_should_be_supported() { SonarScanner scanner = ditProjectSonarScanner(); scanner.setProperty("sonar.java.binaries", "target/../target/clas**, "); ORCHESTRATOR.executeBuild(scanner); assertThat(getNumberOfViolations(PROJECT_KEY_DIT)).isEqualTo(1); }
@Test public void should_exclude_source_files() { assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1()); SonarRunner analysis = SonarRunner.create() .setProfile("it-profile") .setProjectName("SonarAndroidSample") .setProjectKey("SonarAndroidSample") .setProjectVersion("1.0") .setSourceDirs("app/src/main") .setProjectDir(new File("projects/SonarAndroidSample")) .setProperty("skipTests", "true") .setProperty("sonar.global.exclusions", "**/TestViolations.java") .setProperty("sonar.android.lint.report", "lint-results.xml") .setProperty("sonar.import_unknown_files", "true"); orchestrator.executeBuild(analysis); Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample", "violations")); int expectedViolations = 0; if (AndroidTestSuite.sonarqube_version_is_after_5_1()) { // After version 5.1 xml files will be indexed thanks to sonar.import_unknown_files parameter // and so issues can be reported on them. expectedViolations = 4; } assertThat(project.getMeasureIntValue("violations")).isEqualTo(expectedViolations); }
@Test @Ignore("Deactivated awaiting resolution of http://jira.sonarsource.com/browse/JC-145") public void should_run_lint_after_export_and_import_results() throws Exception { assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1()); String response = exportProfile("it-profile"); File baseDir = new File("projects/SonarAndroidSample/app"); FileUtils.write(new File(baseDir, "lint.xml"), response, Charsets.UTF_8); ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "gradle lint"); pb.directory(baseDir); pb.inheritIO(); Process gradleProcess = pb.start(); int exitStatus = gradleProcess.waitFor(); if (exitStatus != 0) { fail("Failed to execute gradle lint."); } SonarRunner analysis = SonarRunner.create() .setProfile("it-profile") .setProjectName("SonarAndroidSample2") .setProjectKey("SonarAndroidSample2") .setProjectVersion("1.0") .setSourceDirs("src/main") .setProjectDir(baseDir) .setProperty("sonar.android.lint.report", "lint-report-build.xml") .setProperty("sonar.import_unknown_files", "true"); orchestrator.executeBuild(analysis); Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample2", "violations")); assertThat(project.getMeasureIntValue("violations")).isEqualTo(2); }
private static String keyFor(String s) { return "project:" + (orchestrator.getConfiguration().getSonarVersion().isGreaterThanOrEquals("4.2") ? "src/" : "") + s; }
@Test public void favourites_web_service() { Sonar adminWsClient = orchestrator.getServer().getAdminWsClient(); // GET (nothing) List<Favourite> favourites = adminWsClient.findAll(new FavouriteQuery()); assertThat(favourites).isEmpty(); // POST (create favourites) Favourite favourite = adminWsClient.create(new FavouriteCreateQuery("sample")); assertThat(favourite).isNotNull(); assertThat(favourite.getKey()).isEqualTo("sample"); adminWsClient.create(new FavouriteCreateQuery("sample:src/main/xoo/sample/Sample.xoo")); // GET (created favourites) favourites = adminWsClient.findAll(new FavouriteQuery()); assertThat(favourites).hasSize(2); List<String> keys = newArrayList( Iterables.transform( favourites, new Function<Favourite, String>() { @Override public String apply(Favourite input) { return input.getKey(); } })); assertThat(keys).containsOnly("sample", "sample:src/main/xoo/sample/Sample.xoo"); // DELETE (a favourite) adminWsClient.delete(new FavouriteDeleteQuery("sample")); favourites = adminWsClient.findAll(new FavouriteQuery()); assertThat(favourites).hasSize(1); assertThat(favourites.get(0).getKey()).isEqualTo("sample:src/main/xoo/sample/Sample.xoo"); }
@Test public void directory_of_classes_in_library_should_be_supported() throws Exception { SonarScanner scanner = ditProjectSonarScanner(); scanner.setProperty("sonar.java.libraries", "target/classes"); ORCHESTRATOR.executeBuild(scanner); assertThat(getNumberOfViolations(PROJECT_KEY_DIT)).isEqualTo(1); }
@Test public void invalid_test_report() throws Exception { BuildResult result = orchestrator.executeBuildQuietly(createBuild("invalid_report.xml")); assertThat(result.isSuccess()).isFalse(); assertThat(result.getLogs()).contains("Cannot feed the data into sonar"); assertProjectMeasures(PROJECT, nullMeasures()); }
@After public void tearDown() { if (orchestrator != null) { orchestrator.stop(); } System.setProperty(HTTPS_PROTOCOLS, initialHttpsProtocols); }
static { OrchestratorBuilder orchestratorBuilder = Orchestrator.builderEnv() // PHP Plugin .addPlugin( FileLocation.of( Iterables.getOnlyElement( Arrays.asList( new File("../../../sonar-php-plugin/target/") .listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".jar") && !name.endsWith("-sources.jar"); } }))) .getAbsolutePath())) .restoreProfileAtStartup(FileLocation.ofClasspath(RESOURCE_DIRECTORY + "profile.xml")) // Custom rules plugin .addPlugin( FileLocation.of( "../plugins/php-custom-rules-plugin/target/php-custom-rules-plugin-1.0-SNAPSHOT.jar")) .restoreProfileAtStartup( FileLocation.ofClasspath(RESOURCE_DIRECTORY + "profile-php-custom-rules.xml")); ORCHESTRATOR = orchestratorBuilder.build(); }
@Test public void should_use_aar_library() { SonarScanner scanner = aarProjectSonarScanner(); scanner.setProperty("sonar.java.libraries", aarPath); ORCHESTRATOR.executeBuild(scanner); assertThat(getNumberOfViolations(PROJECT_KEY_AAR)).isEqualTo(1); }
private Measure getFileMeasure(String metricKey) { Resource resource = orchestrator .getServer() .getWsClient() .find(ResourceQuery.createForMetrics("project:file.js", metricKey)); return resource == null ? null : resource.getMeasure(metricKey); }
private Measure getMeasure(String resourceKey, String metricKey) { Resource resource = orchestrator .getServer() .getWsClient() .find(ResourceQuery.createForMetrics(resourceKey, metricKey)); return resource != null ? resource.getMeasure(metricKey) : null; }