repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import com.google.common.base.Joiner; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.metric.MetricDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Measures.Measure; import org.sonarqube.ws.Measures.SearchWsResponse; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRIC_KEYS; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PROJECT_KEYS; import static org.sonar.test.JsonAssert.assertJson; public class SearchActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final WsActionTester ws = new WsActionTester(new SearchAction(userSession, db.getDbClient())); @Test public void json_example() { ComponentDto project1 = db.components().insertPrivateProject(p -> p.setKey("MY_PROJECT_1").setName("Project 1")).getMainBranchComponent(); ComponentDto project2 = db.components().insertPrivateProject(p -> p.setKey("MY_PROJECT_2").setName("Project 2")).getMainBranchComponent(); ComponentDto project3 = db.components().insertPrivateProject(p -> p.setKey("MY_PROJECT_3").setName("Project 3")).getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project1); userSession.addProjectPermission(UserRole.USER, project2); userSession.addProjectPermission(UserRole.USER, project3); MetricDto complexity = db.measures().insertMetric(m -> m.setKey("complexity").setValueType(INT.name())); db.measures().insertLiveMeasure(project1, complexity, m -> m.setValue(12.0d)); db.measures().insertLiveMeasure(project2, complexity, m -> m.setValue(35.0d)); db.measures().insertLiveMeasure(project3, complexity, m -> m.setValue(42.0d)); MetricDto ncloc = db.measures().insertMetric(m -> m.setKey("ncloc").setValueType(INT.name())); db.measures().insertLiveMeasure(project1, ncloc, m -> m.setValue(114.0d)); db.measures().insertLiveMeasure(project2, ncloc, m -> m.setValue(217.0d)); db.measures().insertLiveMeasure(project3, ncloc, m -> m.setValue(1984.0d)); MetricDto newViolations = db.measures().insertMetric(m -> m.setKey("new_violations").setValueType(INT.name())); db.measures().insertLiveMeasure(project1, newViolations, m -> m.setValue(25.0d)); db.measures().insertLiveMeasure(project2, newViolations, m -> m.setValue(25.0d)); db.measures().insertLiveMeasure(project3, newViolations, m -> m.setValue(255.0d)); List<String> projectKeys = Arrays.asList(project1.getKey(), project2.getKey(), project3.getKey()); String result = ws.newRequest() .setParam(PARAM_PROJECT_KEYS, Joiner.on(",").join(projectKeys)) .setParam(PARAM_METRIC_KEYS, "ncloc, complexity, new_violations") .execute() .getInput(); assertJson(result).withStrictArrayOrder().isSimilarTo(ws.getDef().responseExampleAsString()); } @Test public void return_measures() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); MetricDto coverage = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); db.measures().insertLiveMeasure(project, coverage, m -> m.setValue(15.5d)); SearchWsResponse result = call(singletonList(project.getKey()), singletonList(coverage.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures).hasSize(1); Measure measure = measures.get(0); assertThat(measure.getMetric()).isEqualTo(coverage.getKey()); assertThat(measure.getValue()).isEqualTo("15.5"); } @Test public void return_best_value() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); MetricDto matchBestValue = db.measures().insertMetric(m -> m.setValueType(FLOAT.name()).setBestValue(15.5d)); db.measures().insertLiveMeasure(project, matchBestValue, m -> m.setValue(15.5d)); MetricDto doesNotMatchBestValue = db.measures().insertMetric(m -> m.setValueType(INT.name()).setBestValue(50d)); db.measures().insertLiveMeasure(project, doesNotMatchBestValue, m -> m.setValue(40d)); MetricDto noBestValue = db.measures().insertMetric(m -> m.setValueType(INT.name()).setBestValue(null)); db.measures().insertLiveMeasure(project, noBestValue, m -> m.setValue(123d)); SearchWsResponse result = call(singletonList(project.getKey()), asList(matchBestValue.getKey(), doesNotMatchBestValue.getKey(), noBestValue.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures) .extracting(Measure::getMetric, Measure::getValue, Measure::getBestValue, Measure::hasBestValue) .containsExactlyInAnyOrder( tuple(matchBestValue.getKey(), "15.5", true, true), tuple(doesNotMatchBestValue.getKey(), "40", false, true), tuple(noBestValue.getKey(), "123", false, false)); } @Test public void return_measures_on_new_code_period() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); MetricDto coverage = db.measures().insertMetric(m -> m.setKey("new_metric").setValueType(FLOAT.name())); db.measures().insertLiveMeasure(project, coverage, m -> m.setValue(10d)); SearchWsResponse result = call(singletonList(project.getKey()), singletonList(coverage.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures).hasSize(1); Measure measure = measures.get(0); assertThat(measure.getMetric()).isEqualTo(coverage.getKey()); assertThat(measure.getValue()).isEmpty(); assertThat(measure.getPeriod().getValue()).isEqualTo("10.0"); } @Test public void sort_by_metric_key_then_project_name() { MetricDto coverage = db.measures().insertMetric(m -> m.setKey("coverage").setValueType(FLOAT.name())); MetricDto complexity = db.measures().insertMetric(m -> m.setKey("complexity").setValueType(INT.name())); ComponentDto project1 = db.components().insertPrivateProject(p -> p.setName("C")).getMainBranchComponent(); ComponentDto project2 = db.components().insertPrivateProject(p -> p.setName("A")).getMainBranchComponent(); ComponentDto project3 = db.components().insertPrivateProject(p -> p.setName("B")).getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project1); userSession.addProjectPermission(UserRole.USER, project2); userSession.addProjectPermission(UserRole.USER, project3); db.measures().insertLiveMeasure(project1, coverage, m -> m.setValue(5.5d)); db.measures().insertLiveMeasure(project2, coverage, m -> m.setValue(6.5d)); db.measures().insertLiveMeasure(project3, coverage, m -> m.setValue(7.5d)); db.measures().insertLiveMeasure(project1, complexity, m -> m.setValue(10d)); db.measures().insertLiveMeasure(project2, complexity, m -> m.setValue(15d)); db.measures().insertLiveMeasure(project3, complexity, m -> m.setValue(20d)); SearchWsResponse result = call(asList(project1.getKey(), project2.getKey(), project3.getKey()), asList(coverage.getKey(), complexity.getKey())); assertThat(result.getMeasuresList()).extracting(Measure::getMetric, Measure::getComponent) .containsExactly( tuple(complexity.getKey(), project2.getKey()), tuple(complexity.getKey(), project3.getKey()), tuple(complexity.getKey(), project1.getKey()), tuple(coverage.getKey(), project2.getKey()), tuple(coverage.getKey(), project3.getKey()), tuple(coverage.getKey(), project1.getKey())); } @Test public void return_measures_on_view() { ComponentDto view = db.components().insertPrivatePortfolio(); userSession.addProjectPermission(UserRole.USER, view); MetricDto coverage = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); db.measures().insertLiveMeasure(view, coverage, m -> m.setValue(15.5d)); SearchWsResponse result = call(singletonList(view.getKey()), singletonList(coverage.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures).hasSize(1); Measure measure = measures.get(0); assertThat(measure.getMetric()).isEqualTo(coverage.getKey()); assertThat(measure.getValue()).isEqualTo("15.5"); } @Test public void return_measures_on_application() { ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, application); MetricDto coverage = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); db.measures().insertLiveMeasure(application, coverage, m -> m.setValue(15.5d)); SearchWsResponse result = call(singletonList(application.getKey()), singletonList(coverage.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures).hasSize(1); Measure measure = measures.get(0); assertThat(measure.getMetric()).isEqualTo(coverage.getKey()); assertThat(measure.getValue()).isEqualTo("15.5"); } @Test public void return_measures_on_sub_view() { ComponentDto view = db.components().insertPrivatePortfolio(); ComponentDto subView = db.components().insertComponent(newSubPortfolio(view)); userSession.addProjectPermission(UserRole.USER, view); userSession.addProjectPermission(UserRole.USER, subView); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); db.measures().insertLiveMeasure(subView, metric, m -> m.setValue(15.5d)); SearchWsResponse result = call(singletonList(subView.getKey()), singletonList(metric.getKey())); List<Measure> measures = result.getMeasuresList(); assertThat(measures).hasSize(1); Measure measure = measures.get(0); assertThat(measure.getMetric()).isEqualTo(metric.getKey()); assertThat(measure.getValue()).isEqualTo("15.5"); } @Test public void only_returns_authorized_projects() { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent(); db.measures().insertLiveMeasure(project1, metric, m -> m.setValue(15.5d)); db.measures().insertLiveMeasure(project2, metric, m -> m.setValue(42.0d)); Arrays.stream(new ComponentDto[] {project1}).forEach(p -> userSession.addProjectPermission(UserRole.USER, p)); SearchWsResponse result = call(asList(project1.getKey(), project2.getKey()), singletonList(metric.getKey())); assertThat(result.getMeasuresList()).extracting(Measure::getComponent).containsOnly(project1.getKey()); } @Test public void does_not_return_branch_when_using_db_key() { MetricDto coverage = db.measures().insertMetric(m -> m.setValueType(FLOAT.name())); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project); db.measures().insertLiveMeasure(branch, coverage, m -> m.setValue(10d)); userSession.addProjectPermission(UserRole.USER, project); SearchWsResponse result = call(singletonList(branch.getKey()), singletonList(coverage.getKey())); assertThat(result.getMeasuresList()).isEmpty(); } @Test public void fail_if_no_metric() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); assertThatThrownBy(() -> call(singletonList(project.uuid()), null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'metricKeys' parameter is missing"); } @Test public void fail_if_empty_metric() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); assertThatThrownBy(() -> call(singletonList(project.uuid()), emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Metric keys must be provided"); } @Test public void fail_if_unknown_metric() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(singletonList(project.getKey()), newArrayList("violations", metric.getKey(), "ncloc"))) .isInstanceOf(BadRequestException.class) .hasMessage("The following metrics are not found: ncloc, violations"); } @Test public void fail_if_no_project() { MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(null, singletonList(metric.getKey()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Project keys must be provided"); } @Test public void fail_if_empty_project_key() { MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(emptyList(), singletonList(metric.getKey()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Project keys must be provided"); } @Test public void fail_if_more_than_100_project_keys() { List<String> keys = IntStream.rangeClosed(1, 101) .mapToObj(i -> db.components().insertPrivateProject().getMainBranchComponent()) .map(ComponentDto::getKey) .toList(); MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(keys, singletonList(metric.getKey()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("101 projects provided, more than maximum authorized (100)"); } @Test public void does_not_fail_on_100_projects() { List<String> keys = IntStream.rangeClosed(1, 100) .mapToObj(i -> db.components().insertPrivateProject().getMainBranchComponent()) .map(ComponentDto::getKey) .toList(); MetricDto metric = db.measures().insertMetric(); call(keys, singletonList(metric.getKey())); } @Test public void fail_if_directory() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto dir = db.components().insertComponent(newDirectory(project, "dir")); userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(singletonList(dir.getKey()), singletonList(metric.getKey()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); } @Test public void fail_if_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); userSession.addProjectPermission(UserRole.USER, project); MetricDto metric = db.measures().insertMetric(); assertThatThrownBy(() -> call(singletonList(file.getKey()), singletonList(metric.getKey()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only component of qualifiers [TRK, APP, VW, SVW] are allowed"); } @Test public void definition() { WebService.Action result = ws.getDef(); assertThat(result.key()).isEqualTo("search"); assertThat(result.isPost()).isFalse(); assertThat(result.isInternal()).isTrue(); assertThat(result.since()).isEqualTo("6.2"); assertThat(result.params()).hasSize(2); assertThat(result.responseExampleAsString()).isNotEmpty(); } private SearchWsResponse call(@Nullable List<String> keys, @Nullable List<String> metrics) { TestRequest request = ws.newRequest(); if (keys != null) { request.setParam(PARAM_PROJECT_KEYS, String.join(",", keys)); } if (metrics != null) { request.setParam(PARAM_METRIC_KEYS, String.join(",", metrics)); } return request.executeProtobuf(SearchWsResponse.class); } }
18,129
46.460733
148
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/measure/ws/SearchHistoryActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.ws; import java.util.List; import java.util.stream.LongStream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.measure.MeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.measure.ws.SearchHistoryAction.SearchHistoryRequest; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Common.Paging; import org.sonarqube.ws.Measures.SearchHistoryResponse; import org.sonarqube.ws.Measures.SearchHistoryResponse.HistoryMeasure; import org.sonarqube.ws.Measures.SearchHistoryResponse.HistoryValue; import static java.lang.Double.parseDouble; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.db.component.BranchType.PULL_REQUEST; import static org.sonar.db.component.ComponentDbTester.toProjectDto; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.measure.MeasureTesting.newMeasureDto; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_COMPONENT; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_FROM; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_METRICS; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_TO; import static org.sonar.test.JsonAssert.assertJson; public class SearchHistoryActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final WsActionTester ws = new WsActionTester(new SearchHistoryAction(dbClient, TestComponentFinder.from(db), userSession)); private ComponentDto project; private SnapshotDto analysis; private MetricDto complexityMetric; private MetricDto nclocMetric; private MetricDto newViolationMetric; private MetricDto stringMetric; @Before public void setUp() { project = newPrivateProjectDto(); analysis = db.components().insertProjectAndSnapshot(project); userSession.addProjectPermission(UserRole.USER, project); nclocMetric = insertNclocMetric(); complexityMetric = insertComplexityMetric(); newViolationMetric = insertNewViolationMetric(); stringMetric = insertStringMetric(); } @Test public void empty_response() { project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(singletonList(complexityMetric.getKey())) .build(); SearchHistoryResponse result = call(request); assertThat(result.getMeasuresList()).hasSize(1); assertThat(result.getMeasures(0).getHistoryCount()).isZero(); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal) // pagination is applied to the number of analyses .containsExactly(1, 100, 0); } @Test public void analyses_but_no_measure() { project = db.components().insertPrivateProject().getMainBranchComponent(); analysis = db.components().insertSnapshot(project); userSession.addProjectPermission(UserRole.USER, project); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(singletonList(complexityMetric.getKey())) .build(); SearchHistoryResponse result = call(request); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsExactly(1, 100, 1); assertThat(result.getMeasuresList()).hasSize(1); assertThat(result.getMeasures(0).getHistoryList()).extracting(HistoryValue::hasDate, HistoryValue::hasValue).containsExactly(tuple(true, false)); } @Test public void return_metrics() { dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, analysis).setValue(42.0d)); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey())) .build(); SearchHistoryResponse result = call(request); assertThat(result.getMeasuresList()).hasSize(3) .extracting(HistoryMeasure::getMetric) .containsExactly(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey()); } @Test public void return_measures() { SnapshotDto laterAnalysis = dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(analysis.getCreatedAt() + 42_000)); ComponentDto file = db.components().insertComponent(newFileDto(project)); dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, analysis).setValue(101d), newMeasureDto(complexityMetric, project, laterAnalysis).setValue(100d), newMeasureDto(complexityMetric, file, analysis).setValue(42d), newMeasureDto(nclocMetric, project, analysis).setValue(201d), newMeasureDto(newViolationMetric, project, analysis).setValue(5d), newMeasureDto(newViolationMetric, project, laterAnalysis).setValue(10d)); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey())) .build(); SearchHistoryResponse result = call(request); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal) .containsExactly(1, 100, 2); assertThat(result.getMeasuresList()).extracting(HistoryMeasure::getMetric).hasSize(3) .containsExactly(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey()); String analysisDate = formatDateTime(analysis.getCreatedAt()); String laterAnalysisDate = formatDateTime(laterAnalysis.getCreatedAt()); // complexity measures HistoryMeasure complexityMeasures = result.getMeasures(0); assertThat(complexityMeasures.getMetric()).isEqualTo(complexityMetric.getKey()); assertThat(complexityMeasures.getHistoryList()).extracting(HistoryValue::getDate, HistoryValue::getValue) .containsExactly(tuple(analysisDate, "101"), tuple(laterAnalysisDate, "100")); // ncloc measures HistoryMeasure nclocMeasures = result.getMeasures(1); assertThat(nclocMeasures.getMetric()).isEqualTo(nclocMetric.getKey()); assertThat(nclocMeasures.getHistoryList()).extracting(HistoryValue::getDate, HistoryValue::getValue, HistoryValue::hasValue).containsExactly( tuple(analysisDate, "201", true), tuple(laterAnalysisDate, "", false)); // new_violation measures HistoryMeasure newViolationMeasures = result.getMeasures(2); assertThat(newViolationMeasures.getMetric()).isEqualTo(newViolationMetric.getKey()); assertThat(newViolationMeasures.getHistoryList()).extracting(HistoryValue::getDate, HistoryValue::getValue) .containsExactly(tuple(analysisDate, "5"), tuple(laterAnalysisDate, "10")); } @Test public void pagination_applies_to_analyses() { project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); List<String> analysisDates = LongStream.rangeClosed(1, 9) .mapToObj(i -> dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(i * 1_000_000_000))) .peek(a -> dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, a).setValue(101d))) .map(a -> formatDateTime(a.getCreatedAt())) .toList(); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey())) .setPage(2) .setPageSize(3) .build(); SearchHistoryResponse result = call(request); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsExactly(2, 3, 9); assertThat(result.getMeasures(0).getHistoryList()).extracting(HistoryValue::getDate).containsExactly( analysisDates.get(3), analysisDates.get(4), analysisDates.get(5)); } @Test public void inclusive_from_and_to_dates() { project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); List<String> analysisDates = LongStream.rangeClosed(1, 9) .mapToObj(i -> dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(System2.INSTANCE.now() + i * 1_000_000_000L))) .peek(a -> dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, a).setValue(Double.valueOf(a.getCreatedAt())))) .map(a -> formatDateTime(a.getCreatedAt())) .toList(); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey())) .setFrom(analysisDates.get(1)) .setTo(analysisDates.get(3)) .build(); SearchHistoryResponse result = call(request); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsExactly(1, 100, 3); assertThat(result.getMeasures(0).getHistoryList()).extracting(HistoryValue::getDate).containsExactly( analysisDates.get(1), analysisDates.get(2), analysisDates.get(3)); } @Test public void return_best_values_for_files() { dbClient.metricDao().insert(dbSession, newMetricDto().setKey("optimized").setValueType(ValueType.INT.name()).setOptimizedBestValue(true).setBestValue(456d)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey("new_optimized").setValueType(ValueType.INT.name()).setOptimizedBestValue(true).setBestValue(789d)); db.commit(); ComponentDto file = db.components().insertComponent(newFileDto(project)); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(file.getKey()) .setMetrics(asList("optimized", "new_optimized")) .build(); SearchHistoryResponse result = call(request); assertThat(result.getMeasuresCount()).isEqualTo(2); assertThat(result.getMeasuresList().get(0).getHistoryList()).extracting(HistoryValue::getValue).containsExactly("789"); assertThat(result.getMeasuresList().get(1).getHistoryList()).extracting(HistoryValue::getValue).containsExactly("456"); // Best value is not applied to project request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList("optimized", "new_optimized")) .build(); result = call(request); assertThat(result.getMeasuresList().get(0).getHistoryCount()).isOne(); assertThat(result.getMeasuresList().get(0).getHistory(0).hasDate()).isTrue(); assertThat(result.getMeasuresList().get(0).getHistory(0).hasValue()).isFalse(); } @Test public void do_not_return_unprocessed_analyses() { dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setStatus(STATUS_UNPROCESSED)); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey())) .build(); SearchHistoryResponse result = call(request); // one analysis in setUp method assertThat(result.getPaging().getTotal()).isOne(); } @Test public void branch() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); userSession.addProjectBranchMapping(project.uuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); SnapshotDto analysis = db.components().insertSnapshot(branch); MeasureDto measure = db.measures().insertMeasure(file, analysis, nclocMetric, m -> m.setValue(2d)); SearchHistoryResponse result = ws.newRequest() .setParam(PARAM_COMPONENT, file.getKey()) .setParam(PARAM_BRANCH, "my_branch") .setParam(PARAM_METRICS, "ncloc") .executeProtobuf(SearchHistoryResponse.class); assertThat(result.getMeasuresList()).extracting(HistoryMeasure::getMetric).hasSize(1); HistoryMeasure historyMeasure = result.getMeasures(0); assertThat(historyMeasure.getMetric()).isEqualTo(nclocMetric.getKey()); assertThat(historyMeasure.getHistoryList()) .extracting(m -> parseDouble(m.getValue())) .containsExactlyInAnyOrder(measure.getValue()); } @Test public void pull_request() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("pr-123").setBranchType(PULL_REQUEST)); userSession.addProjectBranchMapping(project.uuid(), branch); ComponentDto file = db.components().insertComponent(newFileDto(branch, project.uuid())); SnapshotDto analysis = db.components().insertSnapshot(branch); MeasureDto measure = db.measures().insertMeasure(file, analysis, nclocMetric, m -> m.setValue(2d)); SearchHistoryResponse result = ws.newRequest() .setParam(PARAM_COMPONENT, file.getKey()) .setParam(PARAM_PULL_REQUEST, "pr-123") .setParam(PARAM_METRICS, "ncloc") .executeProtobuf(SearchHistoryResponse.class); assertThat(result.getMeasuresList()).extracting(HistoryMeasure::getMetric).hasSize(1); HistoryMeasure historyMeasure = result.getMeasures(0); assertThat(historyMeasure.getMetric()).isEqualTo(nclocMetric.getKey()); assertThat(historyMeasure.getHistoryList()) .extracting(m -> parseDouble(m.getValue())) .containsExactlyInAnyOrder(measure.getValue()); } @Test public void fail_if_unknown_metric() { SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(asList(complexityMetric.getKey(), nclocMetric.getKey(), "METRIC_42", "42_METRIC")) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Metrics 42_METRIC, METRIC_42 are not found"); } @Test public void fail_if_not_enough_permissions() { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(singletonList(complexityMetric.getKey())) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_enough_permissions_for_application() { ComponentDto application = db.components().insertPrivateApplication().getMainBranchComponent(); ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn() .registerApplication( toProjectDto(application, 1L), toProjectDto(project1, 1L), toProjectDto(project2, 1L)) .addProjectPermission(UserRole.USER, application, project1); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(application.getKey()) .setMetrics(singletonList(complexityMetric.getKey())) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_unknown_component() { SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent("__UNKNOWN__") .setMetrics(singletonList(complexityMetric.getKey())) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_component_is_removed() { ComponentDto project = db.components().insertComponent(newPrivateProjectDto()); db.components().insertComponent(newFileDto(project).setKey("file-key").setEnabled(false)); userSession.addProjectPermission(UserRole.USER, project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_COMPONENT, "file-key") .setParam(PARAM_METRICS, "ncloc") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Component key 'file-key' not found"); } @Test public void fail_if_branch_does_not_exist() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project)); userSession.addProjectPermission(UserRole.USER, project); db.components().insertProjectBranch(project, b -> b.setKey("my_branch")); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_COMPONENT, file.getKey()) .setParam(PARAM_BRANCH, "another_branch") .setParam(PARAM_METRICS, "ncloc") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch")); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("search_history"); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.isPost()).isFalse(); assertThat(definition.isInternal()).isFalse(); assertThat(definition.since()).isEqualTo("6.3"); assertThat(definition.params()).hasSize(8); Param branch = definition.param("branch"); assertThat(branch.since()).isEqualTo("6.6"); assertThat(branch.isInternal()).isFalse(); assertThat(branch.isRequired()).isFalse(); } @Test public void json_example() { project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, project); long now = parseDateTime("2017-01-23T17:00:53+0100").getTime(); LongStream.rangeClosed(0, 2) .mapToObj(i -> dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(now + i * 24 * 1_000 * 60 * 60))) .forEach(analysis -> dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, analysis).setValue(45d), newMeasureDto(newViolationMetric, project, analysis).setValue(46d), newMeasureDto(nclocMetric, project, analysis).setValue(47d))); db.commit(); String result = ws.newRequest() .setParam(PARAM_COMPONENT, project.getKey()) .setParam(PARAM_METRICS, String.join(",", asList(complexityMetric.getKey(), nclocMetric.getKey(), newViolationMetric.getKey()))) .execute().getInput(); assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString()); } @Test public void measure_without_values() { dbClient.measureDao().insert(dbSession, newMeasureDto(stringMetric, project, analysis).setValue(null).setData(null)); db.commit(); SearchHistoryRequest request = SearchHistoryRequest.builder() .setComponent(project.getKey()) .setMetrics(singletonList(stringMetric.getKey())) .build(); SearchHistoryResponse result = call(request); HistoryMeasure measure = result.getMeasuresList().stream() .filter(m -> m.getMetric().equals(stringMetric.getKey())) .findFirst() .get(); assertThat(measure.getHistoryList()).hasSize(1); assertThat(measure.getHistory(0).hasValue()).isFalse(); } private SearchHistoryResponse call(SearchHistoryRequest request) { TestRequest testRequest = ws.newRequest(); testRequest.setParam(PARAM_COMPONENT, request.getComponent()); testRequest.setParam(PARAM_METRICS, String.join(",", request.getMetrics())); ofNullable(request.getFrom()).ifPresent(from -> testRequest.setParam(PARAM_FROM, from)); ofNullable(request.getTo()).ifPresent(to -> testRequest.setParam(PARAM_TO, to)); ofNullable(request.getPage()).ifPresent(p -> testRequest.setParam(Param.PAGE, String.valueOf(p))); ofNullable(request.getPageSize()).ifPresent(ps -> testRequest.setParam(Param.PAGE_SIZE, String.valueOf(ps))); return testRequest.executeProtobuf(SearchHistoryResponse.class); } private static MetricDto newMetricDtoWithoutOptimization() { return newMetricDto() .setWorstValue(null) .setOptimizedBestValue(false) .setBestValue(null); } private MetricDto insertNclocMetric() { MetricDto metric = dbClient.metricDao().insert(dbSession, newMetricDtoWithoutOptimization() .setKey("ncloc") .setShortName("Lines of code") .setDescription("Non Commenting Lines of Code") .setDomain("Size") .setValueType("INT") .setDirection(-1) .setQualitative(false) .setHidden(false)); db.commit(); return metric; } private MetricDto insertComplexityMetric() { MetricDto metric = dbClient.metricDao().insert(dbSession, newMetricDtoWithoutOptimization() .setKey("complexity") .setShortName("Complexity") .setDescription("Cyclomatic complexity") .setDomain("Complexity") .setValueType("INT") .setDirection(-1) .setQualitative(false) .setHidden(false)); db.commit(); return metric; } private MetricDto insertNewViolationMetric() { MetricDto metric = dbClient.metricDao().insert(dbSession, newMetricDtoWithoutOptimization() .setKey("new_violations") .setShortName("New issues") .setDescription("New Issues") .setDomain("Issues") .setValueType("INT") .setDirection(-1) .setQualitative(true) .setHidden(false)); db.commit(); return metric; } private MetricDto insertStringMetric() { MetricDto metric = dbClient.metricDao().insert(dbSession, newMetricDtoWithoutOptimization() .setKey("a_string") .setShortName("A String") .setValueType("STRING")); db.commit(); return metric; } }
24,717
43.456835
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/metric/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric.ws; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class SearchActionIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final SearchAction underTest = new SearchAction(dbClient); private final WsActionTester ws = new WsActionTester(underTest); @Test public void verify_definition() { Action wsDef = ws.getDef(); assertThat(wsDef.deprecatedSince()).isNull(); assertThat(wsDef.isInternal()).isFalse(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isFalse(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription) .containsExactlyInAnyOrder( tuple("8.4", "Field 'id' in the response is deprecated")); } @Test public void search_metrics_in_database() { db.measures().insertMetric(metricDto -> metricDto .setKey("custom-key-1") .setShortName("custom-name-1") .setValueType("INT") .setDomain("custom-domain-1") .setDescription("custom-description-1") .setDirection(0) .setQualitative(true) .setHidden(false) .setEnabled(true)); db.measures().insertMetric(metricDto -> metricDto .setKey("custom-key-2") .setShortName("custom-name-2") .setValueType("INT") .setDomain("custom-domain-2") .setDescription("custom-description-2") .setDirection(0) .setQualitative(true) .setHidden(false) .setEnabled(true)); db.measures().insertMetric(metricDto -> metricDto .setKey("custom-key-3") .setShortName("custom-name-3") .setValueType("INT") .setDomain("custom-domain-3") .setDescription("custom-description-3") .setDirection(0) .setQualitative(true) .setHidden(false) .setEnabled(true)); TestResponse result = ws.newRequest().execute(); result.assertJson(getClass(), "search_metrics.json"); } @Test public void search_metrics_ordered_by_name_case_insensitive() { insertMetrics("uuid-3", "uuid-1", "uuid-2"); String firstResult = ws.newRequest().setParam(Param.PAGE, "1").setParam(Param.PAGE_SIZE, "1").execute().getInput(); String secondResult = ws.newRequest().setParam(Param.PAGE, "2").setParam(Param.PAGE_SIZE, "1").execute().getInput(); String thirdResult = ws.newRequest().setParam(Param.PAGE, "3").setParam(Param.PAGE_SIZE, "1").execute().getInput(); assertThat(firstResult).contains("uuid-1").doesNotContain("uuid-2").doesNotContain("uuid-3"); assertThat(secondResult).contains("uuid-2").doesNotContain("uuid-1").doesNotContain("uuid-3"); assertThat(thirdResult).contains("uuid-3").doesNotContain("uuid-1").doesNotContain("uuid-2"); } @Test public void search_metrics_with_pagination() { insertMetrics("uuid-1", "uuid-2", "uuid-3", "uuid-4", "uuid-5", "uuid-6", "uuid-7", "uuid-8", "uuid-9", "uuid-10"); TestResponse result = ws.newRequest() .setParam(Param.PAGE, "3") .setParam(Param.PAGE_SIZE, "4") .execute(); assertThat(StringUtils.countMatches(result.getInput(), "name-uuid-")).isEqualTo(2); } private void insertMetrics(String... ids) { for (String id : ids) { db.measures().insertMetric(metricDto -> metricDto.setUuid(id).setShortName("name-" + id).setEnabled(true)); } dbSession.commit(); } }
4,812
35.462121
120
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/monitoring/MetricsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.monitoring; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.BearerPasscode; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.tester.UserSessionRule.standalone; public class MetricsActionIT { @Rule public UserSessionRule userSession = standalone(); @Rule public DbTester db = DbTester.create(); private final BearerPasscode bearerPasscode = mock(BearerPasscode.class); private final SystemPasscode systemPasscode = mock(SystemPasscode.class); private final MetricsAction underTest = new MetricsAction(systemPasscode, bearerPasscode, userSession); private final WsActionTester ws = new WsActionTester(underTest); @Test public void test_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.isInternal()).isFalse(); assertThat(definition.isPost()).isFalse(); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.params()).isEmpty(); } @Test public void no_authentication_throw_insufficient_privileges_error() { TestRequest request = ws.newRequest(); Assertions.assertThatThrownBy(request::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } @Test public void authenticated_non_global_admin_is_forbidden() { userSession.logIn(); TestRequest testRequest = ws.newRequest(); Assertions.assertThatThrownBy(testRequest::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } @Test public void authentication_passcode_is_allowed() { when(systemPasscode.isValid(any())).thenReturn(true); TestResponse response = ws.newRequest().execute(); String content = response.getInput(); assertThat(content) .contains("# HELP sonarqube_health_web_status Tells whether Web process is up or down. 1 for up, 0 for down") .contains("# TYPE sonarqube_health_web_status gauge") .contains("sonarqube_health_web_status 1.0"); } @Test public void authentication_bearer_passcode_is_allowed() { when(bearerPasscode.isValid(any())).thenReturn(true); TestResponse response = ws.newRequest().execute(); String content = response.getInput(); assertThat(content) .contains("# HELP sonarqube_health_web_status Tells whether Web process is up or down. 1 for up, 0 for down") .contains("# TYPE sonarqube_health_web_status gauge") .contains("sonarqube_health_web_status 1.0"); } @Test public void authenticated_global_admin_is_allowed() { userSession.logIn().setSystemAdministrator(); TestResponse response = ws.newRequest().execute(); String content = response.getInput(); assertThat(content) .contains("# HELP sonarqube_health_web_status Tells whether Web process is up or down. 1 for up, 0 for down") .contains("# TYPE sonarqube_health_web_status gauge") .contains("sonarqube_health_web_status 1.0"); } }
4,375
35.773109
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/CaycUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod; import org.junit.Test; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CaycUtilsTest { @Test public void reference_branch_is_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.REFERENCE_BRANCH) .setValue("master"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isTrue(); } @Test public void previous_version_is_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.PREVIOUS_VERSION) .setValue("1.0"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isTrue(); } @Test public void number_of_days_smaller_than_90_is_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("30"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isTrue(); } @Test public void number_of_days_smaller_than_1_is_not_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("0"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isFalse(); } @Test public void number_of_days_bigger_than_90_is_not_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("91"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isFalse(); } @Test public void specific_analysis_is_compliant() { var newCodePeriod = new NewCodePeriodDto() .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("sdfsafsdf"); assertThat(CaycUtils.isNewCodePeriodCompliant(newCodePeriod.getType(), newCodePeriod.getValue())).isTrue(); } @Test public void wrong_number_of_days_format_should_throw_exception() { assertThatThrownBy(() -> CaycUtils.isNewCodePeriodCompliant(NewCodePeriodType.NUMBER_OF_DAYS, "abc")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to parse number of days: abc"); } }
3,297
37.8
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/NewCodeDefinitionResolverTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.db.newcodeperiod.NewCodePeriodType.SPECIFIC_ANALYSIS; public class NewCodeDefinitionResolverTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private static final String DEFAULT_PROJECT_ID = "12345"; private static final String MAIN_BRANCH = "main"; private DbSession dbSession = db.getSession(); private DbClient dbClient = db.getDbClient(); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); @Test public void createNewCodeDefinition_throw_IAE_if_no_valid_type() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, "nonValid", null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid type: nonValid"); } @Test public void createNewCodeDefinition_throw_IAE_if_type_is_not_allowed() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, SPECIFIC_ANALYSIS.name(), null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. `newCodeDefinitionType` can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); } @Test public void createNewCodeDefinition_throw_IAE_if_no_value_for_days() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, NUMBER_OF_DAYS.name(), null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("New code definition type 'NUMBER_OF_DAYS' requires a newCodeDefinitionValue"); } @Test public void createNewCodeDefinition_throw_IAE_if_days_is_invalid() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, NUMBER_OF_DAYS.name(), "unknown")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to parse number of days: unknown"); } @Test public void createNewCodeDefinition_throw_IAE_if_value_is_set_for_reference_branch() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, REFERENCE_BRANCH.name(), "feature/zw")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unexpected value for newCodeDefinitionType 'REFERENCE_BRANCH'"); } @Test public void createNewCodeDefinition_throw_IAE_if_previous_version_type_and_value_provided() { assertThatThrownBy(() -> newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, PREVIOUS_VERSION.name(), "10.2.3")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unexpected value for newCodeDefinitionType 'PREVIOUS_VERSION'"); } @Test public void createNewCodeDefinition_persist_previous_version_type() { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, PREVIOUS_VERSION.name(), null); Optional<NewCodePeriodDto> newCodePeriodDto = dbClient.newCodePeriodDao().selectByProject(dbSession, DEFAULT_PROJECT_ID); assertThat(newCodePeriodDto).map(NewCodePeriodDto::getType).hasValue(PREVIOUS_VERSION); } @Test public void createNewCodeDefinition_return_days_value_for_number_of_days_type() { String numberOfDays = "30"; newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, NUMBER_OF_DAYS.name(), numberOfDays); Optional<NewCodePeriodDto> newCodePeriodDto = dbClient.newCodePeriodDao().selectByProject(dbSession, DEFAULT_PROJECT_ID); assertThat(newCodePeriodDto) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(NUMBER_OF_DAYS, numberOfDays); } @Test public void createNewCodeDefinition_return_branch_value_for_reference_branch_type() { newCodeDefinitionResolver.createNewCodeDefinition(dbSession, DEFAULT_PROJECT_ID, MAIN_BRANCH, REFERENCE_BRANCH.name(), null); Optional<NewCodePeriodDto> newCodePeriodDto = dbClient.newCodePeriodDao().selectByProject(dbSession, DEFAULT_PROJECT_ID); assertThat(newCodePeriodDto) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, MAIN_BRANCH); } @Test public void checkNewCodeDefinitionParam_throw_IAE_if_newCodeDefinitionValue_is_provided_without_newCodeDefinitionType() { assertThatThrownBy(() -> newCodeDefinitionResolver.checkNewCodeDefinitionParam(null, "anyvalue")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("New code definition type is required when new code definition value is provided"); } @Test public void checkNewCodeDefinitionParam_do_not_throw_when_both_value_and_type_are_provided() { assertThatNoException() .isThrownBy(() -> newCodeDefinitionResolver.checkNewCodeDefinitionParam("PREVIOUS_VERSION", "anyvalue")); } }
6,893
45.897959
170
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/ListActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import java.time.Instant; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.documentation.DocumentationLinkGenerator; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.newcodeperiod.NewCodePeriodDao; import org.sonar.db.newcodeperiod.NewCodePeriodDbTester; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.NewCodePeriods; import org.sonarqube.ws.NewCodePeriods.ListWSResponse; import org.sonarqube.ws.NewCodePeriods.ShowWSResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.component.SnapshotTesting.newAnalysis; public class ListActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final ComponentFinder componentFinder = TestComponentFinder.from(db); private final NewCodePeriodDao dao = new NewCodePeriodDao(System2.INSTANCE, UuidFactoryFast.getInstance()); private final NewCodePeriodDbTester tester = new NewCodePeriodDbTester(db); private final DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); private WsActionTester ws; @Before public void setup() { when(documentationLinkGenerator.getDocumentationLink(any())).thenReturn("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); ws = new WsActionTester(new ListAction(dbClient, userSession, componentFinder, dao, documentationLinkGenerator)); } @Test public void test_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.description()).contains("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); assertThat(definition.key()).isEqualTo("list"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.since()).isEqualTo("8.0"); assertThat(definition.isPost()).isFalse(); assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("project"); assertThat(definition.param("project").isRequired()).isTrue(); } @Test public void throw_NFE_if_project_not_found() { assertThatThrownBy(() -> ws.newRequest() .setParam("project", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_FE_if_no_project_permission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.registerProjects(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void list_on_private_project_with_browse_permission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.registerProjects(project); userSession.logIn().addProjectPermission(UserRole.USER, project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(1); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME); } @Test public void list_only_branches() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); createBranches(project, 5, BranchType.BRANCH); createBranches(project, 3, BranchType.PULL_REQUEST); userSession.registerProjects(project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(6); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME, "BRANCH_0", "BRANCH_1", "BRANCH_2", "BRANCH_3", "BRANCH_4"); //check if global default is set assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION); } @Test public void list_inherited_global_settings() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); tester.insert(new NewCodePeriodDto().setType(NewCodePeriodType.SPECIFIC_ANALYSIS).setValue("uuid")); createBranches(project, 5, BranchType.BRANCH); userSession.registerProjects(project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(6); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME, "BRANCH_0", "BRANCH_1", "BRANCH_2", "BRANCH_3", "BRANCH_4"); //check if global default is set assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getValue) .contains("uuid"); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getInherited) .contains(true); } @Test public void list_inherited_project_settings() { ProjectDto projectWithOwnSettings = db.components().insertPublicProject().getProjectDto(); ProjectDto projectWithGlobalSettings = db.components().insertPublicProject().getProjectDto(); tester.insert(new NewCodePeriodDto() .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("global_uuid")); tester.insert(new NewCodePeriodDto() .setProjectUuid(projectWithOwnSettings.getUuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("project_uuid")); createBranches(projectWithOwnSettings, 5, BranchType.BRANCH); userSession.registerProjects(projectWithGlobalSettings, projectWithOwnSettings); ListWSResponse response = ws.newRequest() .setParam("project", projectWithOwnSettings.getKey()) .executeProtobuf(ListWSResponse.class); //verify project with project level settings assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(6); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME, "BRANCH_0", "BRANCH_1", "BRANCH_2", "BRANCH_3", "BRANCH_4"); //check if project setting is set assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getValue) .containsOnly("project_uuid"); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getInherited) .containsOnly(true); //verify project with global level settings response = ws.newRequest() .setParam("project", projectWithGlobalSettings.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isOne(); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .containsOnly(DEFAULT_MAIN_BRANCH_NAME); //check if global setting is set assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getValue) .contains("global_uuid"); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getInherited) .containsOnly(true); } @Test public void list_branch_and_inherited_global_settings() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branchWithOwnSettings = db.components().insertProjectBranch(project, branchDto -> branchDto.setKey("OWN_SETTINGS")); db.components().insertProjectBranch(project, branchDto -> branchDto.setKey("GLOBAL_SETTINGS")); tester.insert(new NewCodePeriodDto() .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("global_uuid")); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setBranchUuid(branchWithOwnSettings.getUuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("branch_uuid")); userSession.registerProjects(project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(3); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME, "OWN_SETTINGS", "GLOBAL_SETTINGS"); Optional<ShowWSResponse> ownSettings = response.getNewCodePeriodsList().stream() .filter(s -> !s.getInherited()) .findFirst(); assertThat(ownSettings) .isNotNull() .isNotEmpty(); assertThat(ownSettings.get().getProjectKey()).isEqualTo(project.getKey()); assertThat(ownSettings.get().getBranchKey()).isEqualTo("OWN_SETTINGS"); assertThat(ownSettings.get().getType()).isEqualTo(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(ownSettings.get().getValue()).isEqualTo("branch_uuid"); assertThat(ownSettings.get().getInherited()).isFalse(); //check if global default is set assertThat(response.getNewCodePeriodsList()) .filteredOn(ShowWSResponse::getInherited) .extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(response.getNewCodePeriodsList()) .filteredOn(ShowWSResponse::getInherited) .extracting(ShowWSResponse::getValue) .contains("global_uuid"); } @Test public void list_branch_and_inherited_project_settings() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branchWithOwnSettings = db.components().insertProjectBranch(project, branchDto -> branchDto.setKey("OWN_SETTINGS")); db.components().insertProjectBranch(project, branchDto -> branchDto.setKey("PROJECT_SETTINGS")); tester.insert(new NewCodePeriodDto() .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("global_uuid")); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("project_uuid")); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setBranchUuid(branchWithOwnSettings.getUuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue("branch_uuid")); userSession.registerProjects(project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(3); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .contains(DEFAULT_MAIN_BRANCH_NAME, "OWN_SETTINGS", "PROJECT_SETTINGS"); Optional<ShowWSResponse> ownSettings = response.getNewCodePeriodsList().stream() .filter(s -> !s.getInherited()) .findFirst(); assertThat(ownSettings) .isNotNull() .isNotEmpty(); assertThat(ownSettings.get().getProjectKey()).isEqualTo(project.getKey()); assertThat(ownSettings.get().getBranchKey()).isEqualTo("OWN_SETTINGS"); assertThat(ownSettings.get().getType()).isEqualTo(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(ownSettings.get().getValue()).isEqualTo("branch_uuid"); assertThat(ownSettings.get().getInherited()).isFalse(); //check if global default is set assertThat(response.getNewCodePeriodsList()) .filteredOn(ShowWSResponse::getInherited) .extracting(ShowWSResponse::getType) .contains(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(response.getNewCodePeriodsList()) .filteredOn(ShowWSResponse::getInherited) .extracting(ShowWSResponse::getValue) .contains("project_uuid"); } @Test public void verify_specific_analysis_effective_value() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, branchDto -> branchDto.setKey("PROJECT_BRANCH")); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(projectData.getMainBranchComponent()) .setUuid("A1") .setCreatedAt(Instant.now().toEpochMilli()) .setProjectVersion("1.2") .setBuildString("1.2.0.322") .setRevision("bfe36592eb7f9f2708b5d358b5b5f33ed535c8cf") ); db.components().insertSnapshot(newAnalysis(projectData.getMainBranchComponent()) .setUuid("A2") .setCreatedAt(Instant.now().toEpochMilli()) .setProjectVersion("1.2") .setBuildString("1.2.0.322") .setRevision("2d6d5d8d5fabe2223f07aa495e794d0401ff4b04") ); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setBranchUuid(branch.getUuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue(analysis.getUuid())); userSession.registerProjects(project); ListWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ListWSResponse.class); assertThat(response).isNotNull(); assertThat(response.getNewCodePeriodsCount()).isEqualTo(2); assertThat(response.getNewCodePeriodsList()).extracting(ShowWSResponse::getBranchKey) .containsOnly(DEFAULT_MAIN_BRANCH_NAME, "PROJECT_BRANCH"); ShowWSResponse result = response.getNewCodePeriodsList().get(0); assertThat(result.getType()).isEqualTo(NewCodePeriods.NewCodePeriodType.SPECIFIC_ANALYSIS); assertThat(result.getValue()).isEqualTo("A1"); assertThat(result.getProjectKey()).isEqualTo(project.getKey()); assertThat(result.getBranchKey()).isEqualTo("PROJECT_BRANCH"); assertThat(result.getEffectiveValue()).isEqualTo(DateUtils.formatDateTime(analysis.getCreatedAt())); } private void createBranches(ProjectDto project, int numberOfBranches, BranchType branchType) { for (int branchCount = 0; branchCount < numberOfBranches; branchCount++) { String branchKey = String.format("%s_%d", branchType.name(), branchCount); db.components().insertProjectBranch(project, branchDto -> branchDto.setKey(branchKey).setBranchType(branchType)); } } }
17,919
41.768496
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/SetActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.documentation.DocumentationLinkGenerator; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.newcodeperiod.NewCodePeriodDao; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; @RunWith(DataProviderRunner.class) public class SetActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private ComponentFinder componentFinder = TestComponentFinder.from(db); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private NewCodePeriodDao dao = new NewCodePeriodDao(System2.INSTANCE, UuidFactoryFast.getInstance()); private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); private WsActionTester ws; @Before public void setup() { when(documentationLinkGenerator.getDocumentationLink(any())).thenReturn("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); ws = new WsActionTester(new SetAction(dbClient, userSession, componentFinder, editionProvider, dao, documentationLinkGenerator)); } @Test public void test_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.description()).contains("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); assertThat(definition.key()).isEqualTo("set"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.since()).isEqualTo("8.0"); assertThat(definition.isPost()).isTrue(); assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("value", "type", "project", "branch"); assertThat(definition.param("value").isRequired()).isFalse(); assertThat(definition.param("type").isRequired()).isTrue(); assertThat(definition.param("project").isRequired()).isFalse(); assertThat(definition.param("branch").isRequired()).isFalse(); } // validation of type @Test public void throw_IAE_if_no_type_specified() { assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'type' parameter is missing"); } @Test public void throw_IAE_if_type_is_invalid() { assertThatThrownBy(() -> ws.newRequest().setParam("type", "unknown").execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid type: unknown"); } @Test public void throw_IAE_if_type_is_invalid_for_global() { assertThatThrownBy(() -> ws.newRequest().setParam("type", "specific_analysis").execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Overall setting can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS]"); } @Test public void throw_IAE_if_type_is_invalid_for_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid type 'SPECIFIC_ANALYSIS'. Projects can only be set with types: [PREVIOUS_VERSION, NUMBER_OF_DAYS, REFERENCE_BRANCH]"); } @Test public void throw_IAE_if_no_value_for_days() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("type", "number_of_days") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("New code definition type 'NUMBER_OF_DAYS' requires a value"); } @Test public void throw_IAE_if_no_value_for_analysis() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("New code definition type 'SPECIFIC_ANALYSIS' requires a value"); } @Test public void throw_IAE_if_days_is_invalid() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "unknown") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to parse number of days: unknown"); } @Test public void throw_IAE_if_setting_is_not_cayc_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); TestRequest request = ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "92"); assertThatThrownBy(() -> request .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to set the New Code Definition. The given value is not compatible with the Clean as You Code methodology. " + "Please refer to the documentation for compliant options."); } @Test public void no_error_if_setting_is_cayc_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("value", "90") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "90"); } @Test public void throw_IAE_if_analysis_is_not_found() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Analysis 'unknown' is not found"); } @Test public void throw_IAE_if_analysis_doesnt_belong_to_branch() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); ComponentDto branch = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("branch")); SnapshotDto analysisMaster = db.components().insertSnapshot(project); SnapshotDto analysisBranch = db.components().insertSnapshot(branch); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", DEFAULT_MAIN_BRANCH_NAME) .setParam("value", analysisBranch.getUuid()) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Analysis '" + analysisBranch.getUuid() + "' does not belong to branch '" + DEFAULT_MAIN_BRANCH_NAME + "' of project '" + project.getKey() + "'"); } // validation of project/branch @Test public void throw_IAE_if_branch_is_specified_without_project() { assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_NFE_if_project_not_found() { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .setParam("project", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_NFE_if_branch_not_found() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .setParam("branch", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @Test public void throw_NFE_if_no_project_permission() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void throw_NFE_if_no_system_permission() { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } // success cases @Test public void set_global_period_to_previous_version() { logInAsSystemAdministrator(); ws.newRequest() .setParam("type", "previous_version") .execute(); assertTableContainsOnly(null, null, NewCodePeriodType.PREVIOUS_VERSION, null); } @Test public void set_project_period_to_number_of_days() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("value", "5") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "5"); } @Test @UseDataProvider("provideNewCodePeriodTypeAndValue") public void never_set_project_value_in_community_edition(NewCodePeriodType type, @Nullable String value) { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); if (value != null && NewCodePeriodType.SPECIFIC_ANALYSIS.equals(type)) { db.components().insertSnapshot(project, snapshotDto -> snapshotDto.setUuid(value)); } logInAsProjectAdministrator(project); TestRequest request = ws.newRequest() .setParam("project", project.getKey()) .setParam("type", type.name()); if (value != null) { request.setParam("value", value); } request.execute(); assertTableContainsOnly(project.getUuid(), projectData.getMainBranchComponent().uuid(), type, value); } @DataProvider public static Object[][] provideNewCodePeriodTypeAndValue() { return new Object[][] { {NewCodePeriodType.NUMBER_OF_DAYS, "5"}, {NewCodePeriodType.SPECIFIC_ANALYSIS, "analysis-uuid"}, {NewCodePeriodType.PREVIOUS_VERSION, null}, {NewCodePeriodType.REFERENCE_BRANCH, "master"} }; } @Test public void set_project_twice_period_to_number_of_days() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.PREVIOUS_VERSION, null); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "number_of_days") .setParam("value", "5") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "5"); } @Test public void set_branch_period_to_analysis() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); ComponentDto branch = db.components().insertProjectBranch(projectData.getMainBranchComponent(), b -> b.setKey("branch")); SnapshotDto analysisMaster = db.components().insertSnapshot(project); SnapshotDto analysisBranch = db.components().insertSnapshot(branch); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", "branch") .setParam("value", analysisBranch.getUuid()) .execute(); assertTableContainsOnly(project.getUuid(), branch.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, analysisBranch.getUuid()); } @Test public void set_branch_period_twice_to_analysis() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); BranchDto branch = db.components().insertProjectBranch(projectData.getProjectDto(), b -> b.setKey("branch")); SnapshotDto analysisMaster = db.components().insertSnapshot(project); SnapshotDto analysisBranch = db.components().insertSnapshot(branch); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "specific_analysis") .setParam("branch", "branch") .setParam("value", analysisBranch.getUuid()) .execute(); ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .setParam("branch", "branch") .execute(); assertTableContainsOnly(project.getUuid(), branch.getUuid(), NewCodePeriodType.PREVIOUS_VERSION, null); } private void assertTableContainsOnly(@Nullable String projectUuid, @Nullable String branchUuid, NewCodePeriodType type, @Nullable String value) { assertThat(db.countRowsOfTable(dbSession, "new_code_periods")).isOne(); assertThat(db.selectFirst(dbSession, "select project_uuid, branch_uuid, type, value from new_code_periods")) .containsOnly(entry("PROJECT_UUID", projectUuid), entry("BRANCH_UUID", branchUuid), entry("TYPE", type.name()), entry("VALUE", value)); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } }
17,397
38.451247
155
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/ShowActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.documentation.DocumentationLinkGenerator; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.newcodeperiod.NewCodePeriodDao; import org.sonar.db.newcodeperiod.NewCodePeriodDbTester; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.NewCodePeriods; import org.sonarqube.ws.NewCodePeriods.ShowWSResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ShowActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = db.getDbClient(); private ComponentFinder componentFinder = TestComponentFinder.from(db); private NewCodePeriodDao dao = new NewCodePeriodDao(System2.INSTANCE, UuidFactoryFast.getInstance()); private NewCodePeriodDbTester tester = new NewCodePeriodDbTester(db); private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); private WsActionTester ws; @Before public void setup(){ when(documentationLinkGenerator.getDocumentationLink(any())).thenReturn("https://docs.sonarqube.org/latest/project-administration/defining-new-code/"); ws = new WsActionTester(new ShowAction(dbClient, userSession, componentFinder, dao, documentationLinkGenerator)); } @Test public void test_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.description()).contains("https://docs.sonarqube.org/latest/project-administration/defining-new-code/"); assertThat(definition.key()).isEqualTo("show"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.since()).isEqualTo("8.0"); assertThat(definition.isPost()).isFalse(); assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("project", "branch"); assertThat(definition.param("project").isRequired()).isFalse(); assertThat(definition.param("branch").isRequired()).isFalse(); } @Test public void throw_IAE_if_branch_is_specified_without_project() { assertThatThrownBy(() -> ws.newRequest() .setParam("branch", "branch") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_FE_if_no_project_permission() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void throw_FE_if_project_issue_admin() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectIssueAdmin(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void show_global_setting() { tester.insert(new NewCodePeriodDto().setType(NewCodePeriodType.PREVIOUS_VERSION)); ShowWSResponse response = ws.newRequest() .executeProtobuf(ShowWSResponse.class); assertResponse(response, "", "", NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION, "", false); } @Test public void show_project_setting() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("4")); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "4", false); } @Test public void show_branch_setting() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setBranchUuid(branch.getUuid()) .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("1")); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "branch", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "1", false); } @Test public void show_inherited_project_setting() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); tester.insert(new NewCodePeriodDto().setType(NewCodePeriodType.PREVIOUS_VERSION)); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "", NewCodePeriods.NewCodePeriodType.PREVIOUS_VERSION, "", true); } @Test public void show_inherited_branch_setting_from_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); tester.insert(new NewCodePeriodDto() .setProjectUuid(project.getUuid()) .setType(NewCodePeriodType.NUMBER_OF_DAYS) .setValue("1")); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "branch", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "1", true); } @Test public void show_inherited_branch_setting_from_global() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); BranchDto branchDto = db.components().insertProjectBranch(project, b -> b.setKey("branch")); tester.insert(new NewCodePeriodDto().setType(NewCodePeriodType.NUMBER_OF_DAYS).setValue("3")); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "branch", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "3", true); } @Test public void show_inherited_if_project_not_found() { tester.insert(new NewCodePeriodDto().setType(NewCodePeriodType.NUMBER_OF_DAYS).setValue("3")); ShowWSResponse response = ws.newRequest() .setParam("project", "unknown") .executeProtobuf(ShowWSResponse.class); assertResponse(response, "", "", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "3", true); } @Test public void show_inherited_if_branch_not_found() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectScan(project); tester.insert(project.getUuid(), NewCodePeriodType.NUMBER_OF_DAYS, "3"); ShowWSResponse response = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "unknown") .executeProtobuf(ShowWSResponse.class); assertResponse(response, project.getKey(), "", NewCodePeriods.NewCodePeriodType.NUMBER_OF_DAYS, "3", true); } private void assertResponse(ShowWSResponse response, String projectKey, String branchKey, NewCodePeriods.NewCodePeriodType type, String value, boolean inherited) { assertThat(response.getBranchKey()).isEqualTo(branchKey); assertThat(response.getProjectKey()).isEqualTo(projectKey); assertThat(response.getInherited()).isEqualTo(inherited); assertThat(response.getValue()).isEqualTo(value); assertThat(response.getType()).isEqualTo(type); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } private void logInAsProjectScan(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.SCAN, project); } private void logInAsProjectIssueAdmin(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ISSUE_ADMIN, project); } }
10,241
38.241379
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/newcodeperiod/ws/UnsetActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.newcodeperiod.ws; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.documentation.DocumentationLinkGenerator; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ProjectData; import org.sonar.db.newcodeperiod.NewCodePeriodDao; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UnsetActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private ComponentFinder componentFinder = TestComponentFinder.from(db); private NewCodePeriodDao dao = new NewCodePeriodDao(System2.INSTANCE, UuidFactoryFast.getInstance()); private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private DocumentationLinkGenerator documentationLinkGenerator = mock(DocumentationLinkGenerator.class); private WsActionTester ws; @Before public void setup(){ when(documentationLinkGenerator.getDocumentationLink(any())).thenReturn("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); ws = new WsActionTester(new UnsetAction(dbClient, userSession, componentFinder, editionProvider, dao, documentationLinkGenerator)); } @Test public void test_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.description()).contains("https://docs.sonarqube.org/9.9/project-administration/defining-new-code/"); assertThat(definition.key()).isEqualTo("unset"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.since()).isEqualTo("8.0"); assertThat(definition.isPost()).isTrue(); assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("project", "branch"); assertThat(definition.param("project").isRequired()).isFalse(); assertThat(definition.param("branch").isRequired()).isFalse(); } // validation of project/branch @Test public void throw_IAE_if_branch_is_specified_without_project() { TestRequest request = ws.newRequest() .setParam("branch", "branch"); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("If branch key is specified, project key needs to be specified too"); } @Test public void throw_NFE_if_project_not_found() { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .setParam("project", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project 'unknown' not found"); } @Test public void throw_NFE_if_branch_not_found() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .setParam("branch", "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Branch 'unknown' in project '" + project.getKey() + "' not found"); } // permission @Test public void throw_NFE_if_no_project_permission() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .setParam("type", "previous_version") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void throw_NFE_if_no_system_permission() { assertThatThrownBy(() -> ws.newRequest() .setParam("type", "previous_version") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } // success cases @Test public void delete_global_period() { logInAsSystemAdministrator(); ws.newRequest() .execute(); assertTableEmpty(); } @Test public void delete_project_period() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .execute(); assertTableEmpty(); } @Test public void delete_project_period_twice() { ProjectDto project1 = db.components().insertPublicProject().getProjectDto(); ProjectDto project2 = db.components().insertPublicProject().getProjectDto(); db.newCodePeriods().insert(project1.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid1"); db.newCodePeriods().insert(project2.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid2"); logInAsProjectAdministrator(project1); ws.newRequest() .setParam("project", project1.getKey()) .execute(); assertTableContainsOnly(project2.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid2"); ws.newRequest() .setParam("project", project1.getKey()) .execute(); assertTableContainsOnly(project2.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid2"); } @Test public void delete_branch_period() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "20"); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid2"); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "20"); } @Test public void delete_branch_and_project_period_in_community_edition() { ProjectData projectData = db.components().insertPublicProject(); ProjectDto project = projectData.getProjectDto(); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid1"); db.newCodePeriods().insert(project.getUuid(), projectData.getMainBranchComponent().uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid2"); when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .execute(); assertTableEmpty(); } @Test public void throw_IAE_if_unset_branch_NCD_and_project_NCD_not_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "97"); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); TestRequest request = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch"); logInAsProjectAdministrator(project); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your project " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your project New Code Definition"); } @Test public void throw_IAE_if_unset_branch_NCD_and_no_project_NCD_and_instance_NCD_not_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(null, null, NewCodePeriodType.NUMBER_OF_DAYS, "97"); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); TestRequest request = ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch"); logInAsProjectAdministrator(project); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your instance " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your instance New Code Definition"); } @Test public void throw_IAE_if_unset_project_NCD_and_instance_NCD_not_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.newCodePeriods().insert(null, null, NewCodePeriodType.NUMBER_OF_DAYS, "97"); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); logInAsProjectAdministrator(project); TestRequest request = ws.newRequest() .setParam("project", project.getKey()); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to unset the New Code Definition. Your instance " + "New Code Definition is not compatible with the Clean as You Code methodology. Please update your instance New Code Definition"); } @Test public void do_not_throw_IAE_if_unset_project_NCD_and_no_instance_NCD() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .execute(); assertTableEmpty(); } @Test public void do_not_throw_IAE_if_unset_branch_NCD_and_project_NCD_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.PREVIOUS_VERSION, null); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.PREVIOUS_VERSION, null); } @Test public void do_not_throw_IAE_if_unset_branch_NCD_and_project_NCD_not_compliant_and_no_branch_NCD() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "93"); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .execute(); assertTableContainsOnly(project.getUuid(), null, NewCodePeriodType.NUMBER_OF_DAYS, "93"); } @Test public void do_not_throw_IAE_if_unset_branch_NCD_and_no_project_NCD_and_instance_NCD_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); db.newCodePeriods().insert(null, null, NewCodePeriodType.PREVIOUS_VERSION, null); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .execute(); assertTableContainsOnly(null, null, NewCodePeriodType.PREVIOUS_VERSION, null); } @Test public void do_not_throw_IAE_if_unset_branch_NCD_and_no_project_NCD_and_no_instance() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(project.getUuid(), branch.getUuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "uuid"); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .setParam("branch", "branch") .execute(); assertTableEmpty(); } @Test public void do_not_throw_IAE_if_unset_project_NCD_and_instance_NCD_compliant() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(null, null, NewCodePeriodType.PREVIOUS_VERSION, null); db.newCodePeriods().insert(project.getUuid(), null, NewCodePeriodType.PREVIOUS_VERSION, null); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .execute(); assertTableContainsOnly(null, null, NewCodePeriodType.PREVIOUS_VERSION, null); } @Test public void do_not_throw_IAE_if_unset_project_NCD_and_instance_NCD_not_compliant_and_no_project_NCD() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch")); db.newCodePeriods().insert(null, null, NewCodePeriodType.NUMBER_OF_DAYS, "93"); logInAsProjectAdministrator(project); ws.newRequest() .setParam("project", project.getKey()) .execute(); assertTableContainsOnly(null, null, NewCodePeriodType.NUMBER_OF_DAYS, "93"); } private void assertTableEmpty() { assertThat(db.countRowsOfTable(dbSession, "new_code_periods")).isZero(); } private void assertTableContainsOnly(@Nullable String projectUuid, @Nullable String branchUuid, NewCodePeriodType type, @Nullable String value) { assertThat(db.countRowsOfTable(dbSession, "new_code_periods")).isOne(); assertThat(db.selectFirst(dbSession, "select project_uuid, branch_uuid, type, value from new_code_periods")) .containsOnly(entry("PROJECT_UUID", projectUuid), entry("BRANCH_UUID", branchUuid), entry("TYPE", type.name()), entry("VALUE", value)); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } }
16,544
40.156716
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/AddActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.ComponentTesting.newPortfolio; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_CHANNEL; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_LOGIN; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_PROJECT; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_TYPE; public class AddActionIT { private static final String NOTIF_MY_NEW_ISSUES = "Dispatcher1"; private static final String NOTIF_NEW_ISSUES = "Dispatcher2"; private static final String NOTIF_NEW_QUALITY_GATE_STATUS = "Dispatcher3"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final NotificationChannel emailChannel = new FakeNotificationChannel("EmailChannel"); private final NotificationChannel twitterChannel = new FakeNotificationChannel("TwitterChannel"); // default channel, based on class simple name private final NotificationChannel defaultChannel = new FakeNotificationChannel("EmailNotificationChannel"); private final Dispatchers dispatchers = mock(Dispatchers.class); private final WsActionTester ws = new WsActionTester(new AddAction(new NotificationCenter( new NotificationDispatcherMetadata[] {}, new NotificationChannel[] {emailChannel, twitterChannel, defaultChannel}), new NotificationUpdater(dbClient), dispatchers, dbClient, TestComponentFinder.from(db), userSession)); @Test public void add_to_email_channel_by_default() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, null, null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), null); } @Test public void add_to_a_specific_channel() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); call(NOTIF_NEW_QUALITY_GATE_STATUS, twitterChannel.getKey(), null, null); db.notifications().assertExists(twitterChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, userSession.getUuid(), null); } @Test public void add_notification_on_private_with_USER_permission() { UserDto user = db.users().insertUser(); userSession.logIn(user); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.addProjectPermission(USER, project); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, project.getKey(), null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), project); } @Test public void add_notification_on_public_project() { UserDto user = db.users().insertUser(); userSession.logIn(user); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.registerProjects(project); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, project.getKey(), null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), project); } @Test public void add_a_global_notification_when_a_project_one_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES)); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.addProjectPermission(USER, project); call(NOTIF_MY_NEW_ISSUES, null, project.getKey(), null); call(NOTIF_MY_NEW_ISSUES, null, null, null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), project); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), null); } @Test public void add_a_notification_on_private_project_when_a_global_one_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); call(NOTIF_MY_NEW_ISSUES, null, null, null); userSession.addProjectPermission(USER, project); call(NOTIF_MY_NEW_ISSUES, null, project.getKey(), null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), project); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), null); } @Test public void add_a_notification_on_public_project_when_a_global_one_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.registerProjects(project); call(NOTIF_MY_NEW_ISSUES, null, null, null); call(NOTIF_MY_NEW_ISSUES, null, project.getKey(), null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), project); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, userSession.getUuid(), null); } @Test public void http_no_content() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); TestResponse result = call(NOTIF_MY_NEW_ISSUES, null, null, null); assertThat(result.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void add_a_notification_to_a_user_as_system_administrator() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, null, user.getLogin()); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user.getUuid(), null); } @Test public void fail_if_login_is_provided_and_unknown() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, "LOGIN 404")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("User 'LOGIN 404' not found"); } @Test public void fail_if_login_provided_and_not_system_administrator() { UserDto user = db.users().insertUser(); userSession.logIn(user).setNonSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); String login = user.getLogin(); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, login)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_project_provided_and_not_project_user() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); String projectKey = project.getKey(); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, projectKey, null)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_notification_already_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); call(NOTIF_MY_NEW_ISSUES, null, null, null); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Notification already added"); } @Test public void fail_when_unknown_channel() { assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, "Channel42", null, null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_unknown_global_dispatcher() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call("Dispatcher42", null, null, null)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1]"); } @Test public void fail_when_unknown_project_dispatcher_on_private_project() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.addProjectPermission(USER, project); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); String projectKey = project.getKey(); assertThatThrownBy(() -> call("Dispatcher42", null, projectKey, null)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); } @Test public void fail_when_unknown_project_dispatcher_on_public_project() { UserDto user = db.users().insertUser(); userSession.logIn(user); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES)); String projectKey = project.getKey(); assertThatThrownBy(() -> call("Dispatcher42", null, projectKey, null)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2]"); } @Test public void fail_when_no_dispatcher() { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_project_is_unknown() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, "Project-42", null)) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_component_is_not_a_project() { UserDto user = db.users().insertUser(); userSession.logIn(user); db.components().insertPortfolioAndSnapshot(newPortfolio().setKey("VIEW_1")); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, "VIEW_1", null)) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project 'VIEW_1' not found"); } @Test public void fail_when_not_authenticated() { userSession.anonymous(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, null, null)) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_when_user_does_not_have_USER_permission_on_private_project() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().setNonSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); String key = project.getKey(); String login = userSession.getLogin(); assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, key, login)) .isInstanceOf(ForbiddenException.class); } private TestResponse call(String type, @Nullable String channel, @Nullable String project, @Nullable String login) { TestRequest request = ws.newRequest(); request.setParam(PARAM_TYPE, type); ofNullable(channel).ifPresent(channel1 -> request.setParam(PARAM_CHANNEL, channel1)); ofNullable(project).ifPresent(project1 -> request.setParam(PARAM_PROJECT, project1)); ofNullable(login).ifPresent(login1 -> request.setParam(PARAM_LOGIN, login1)); return request.execute(); } private static class FakeNotificationChannel extends NotificationChannel { private final String key; private FakeNotificationChannel(String key) { this.key = key; } @Override public String getKey() { return this.key; } @Override public boolean deliver(Notification notification, String username) { // do nothing return true; } } }
16,174
42.481183
121
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/ListActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Notifications.ListResponse; import org.sonarqube.ws.Notifications.Notification; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.test.JsonAssert.assertJson; public class ListActionIT { private static final String NOTIF_MY_NEW_ISSUES = "MyNewIssues"; private static final String NOTIF_NEW_ISSUES = "NewIssues"; private static final String NOTIF_NEW_QUALITY_GATE_STATUS = "NewQualityGateStatus"; @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public final DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final NotificationChannel emailChannel = new FakeNotificationChannel("EmailChannel"); private final NotificationChannel twitterChannel = new FakeNotificationChannel("TwitterChannel"); private final NotificationUpdater notificationUpdater = new NotificationUpdater(dbClient); private final Dispatchers dispatchers = mock(Dispatchers.class); private final WsActionTester ws = new WsActionTester(new ListAction(new NotificationCenter( new NotificationDispatcherMetadata[] {}, new NotificationChannel[] {emailChannel, twitterChannel}), dbClient, userSession, dispatchers)); @Test public void channels() { UserDto user = db.users().insertUser(); userSession.logIn(user); ListResponse result = call(); assertThat(result.getChannelsList()).containsExactly(emailChannel.getKey(), twitterChannel.getKey()); } @Test public void overall_dispatchers() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); ListResponse result = call(); assertThat(result.getGlobalTypesList()).containsExactly(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS); } @Test public void per_project_dispatchers() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); ListResponse result = call(); assertThat(result.getPerProjectTypesList()).containsExactly(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS); } @Test public void filter_unauthorized_projects() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectData project = db.components().insertPrivateProject(); db.users().insertProjectPermissionOnUser(user, USER, project.getMainBranchComponent()); ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto(); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project.getProjectDto()); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, anotherProject); dbSession.commit(); ListResponse result = call(); assertThat(result.getNotificationsList()).extracting(Notification::getProject).containsOnly(project.getProjectDto().getKey()); } @Test public void filter_channels() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, "Unknown Channel", NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); ListResponse result = call(); assertThat(result.getNotificationsList()).extracting(Notification::getChannel).containsOnly(emailChannel.getKey()); } @Test public void filter_overall_dispatchers() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), "Unknown Notification", user, null); dbSession.commit(); ListResponse result = call(); assertThat(result.getNotificationsList()).extracting(Notification::getType).containsOnly(NOTIF_MY_NEW_ISSUES); } @Test public void filter_per_project_dispatchers() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectData project = db.components().insertPrivateProject(); db.users().insertProjectPermissionOnUser(user, USER, project.getMainBranchComponent()); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project.getProjectDto()); notificationUpdater.add(dbSession, emailChannel.getKey(), "Unknown Notification", user, project.getProjectDto()); dbSession.commit(); ListResponse result = call(); assertThat(result.getNotificationsList()) .extracting(Notification::getType) .containsOnly(NOTIF_MY_NEW_ISSUES); } @Test public void order_with_global_then_by_channel_and_dispatcher() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(user, USER, project); notificationUpdater.add(dbSession, twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, user, project); dbSession.commit(); ListResponse result = call(); assertThat(result.getNotificationsList()) .extracting(Notification::getChannel, Notification::getType, Notification::getProject) .containsExactly( tuple(emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, ""), tuple(emailChannel.getKey(), NOTIF_NEW_ISSUES, ""), tuple(twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, ""), tuple(emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, project.getKey()), tuple(emailChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, project.getKey()), tuple(twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, project.getKey())); } @Test public void list_user_notifications_as_system_admin() { UserDto user = db.users().insertUser(); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); userSession.logIn(user).setSystemAdministrator(); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_NEW_ISSUES, user, null); dbSession.commit(); ListResponse result = call(user.getLogin()); assertThat(result.getNotificationsList()) .extracting(Notification::getType) .containsOnly(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES); } @Test public void fail_if_login_and_not_system_admin() { UserDto user = db.users().insertUser(); userSession.logIn(user).setNonSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); String userLogin = user.getLogin(); assertThatThrownBy(() -> call(userLogin)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_login_is_provided_and_unknown() { userSession.logIn().setSystemAdministrator(); assertThatThrownBy(() -> call("LOGIN 404")) .isInstanceOf(NotFoundException.class) .hasMessage("User 'LOGIN 404' not found"); } @Test public void json_example() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); ProjectData projectData = db.components().insertPrivateProject(p -> p.setKey(KEY_PROJECT_EXAMPLE_001).setName("My Project")); ProjectDto project = projectData.getProjectDto(); db.users().insertProjectPermissionOnUser(user, USER, projectData.getMainBranchComponent()); notificationUpdater.add(dbSession, twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_NEW_ISSUES, user, null); notificationUpdater.add(dbSession, twitterChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); notificationUpdater.add(dbSession, emailChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, user, project); dbSession.commit(); String result = ws.newRequest().execute().getInput(); assertJson(ws.getDef().responseExampleAsString()) .withStrictArrayOrder() .isSimilarTo(result); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("list"); assertThat(definition.isPost()).isFalse(); assertThat(definition.since()).isEqualTo("6.3"); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.params()).hasSize(1); WebService.Param loginParam = definition.param("login"); assertThat(loginParam.since()).isEqualTo("6.4"); assertThat(loginParam.isRequired()).isFalse(); } @Test public void fail_when_not_authenticated() { userSession.anonymous(); assertThatThrownBy(this::call) .isInstanceOf(UnauthorizedException.class); } private ListResponse call() { return ws.newRequest().executeProtobuf(ListResponse.class); } private ListResponse call(String login) { return ws.newRequest().setParam("login", login).executeProtobuf(ListResponse.class); } private static class FakeNotificationChannel extends NotificationChannel { private final String key; private FakeNotificationChannel(String key) { this.key = key; } @Override public String getKey() { return this.key; } @Override public boolean deliver(org.sonar.api.notifications.Notification notification, String username) { // do nothing return true; } } }
13,513
42.175719
134
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/notification/ws/RemoveActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.ws.RemoveAction.RemoveRequest; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newPortfolio; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_CHANNEL; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_LOGIN; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_PROJECT; import static org.sonar.server.notification.ws.NotificationsWsParameters.PARAM_TYPE; public class RemoveActionIT { private static final String NOTIF_MY_NEW_ISSUES = "Dispatcher1"; private static final String NOTIF_NEW_ISSUES = "Dispatcher2"; private static final String NOTIF_NEW_QUALITY_GATE_STATUS = "Dispatcher3"; @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public final DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final NotificationChannel emailChannel = new FakeNotificationChannel("EmailChannel"); private final NotificationChannel twitterChannel = new FakeNotificationChannel("TwitterChannel"); // default channel, based on class simple name private final NotificationChannel defaultChannel = new FakeNotificationChannel("EmailNotificationChannel"); private final NotificationUpdater notificationUpdater = new NotificationUpdater(dbClient); private final Dispatchers dispatchers = mock(Dispatchers.class); private final RemoveRequest request = new RemoveRequest().setType(NOTIF_MY_NEW_ISSUES); private final WsActionTester ws = new WsActionTester(new RemoveAction(new NotificationCenter( new NotificationDispatcherMetadata[] {}, new NotificationChannel[] {emailChannel, twitterChannel, defaultChannel}), notificationUpdater, dispatchers, dbClient, TestComponentFinder.from(db), userSession)); @Test public void remove_to_email_channel_by_default() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); call(request); db.notifications().assertDoesNotExist(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user.getUuid(), null); } @Test public void remove_from_a_specific_channel() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_NEW_QUALITY_GATE_STATUS)); notificationUpdater.add(dbSession, twitterChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, user, null); dbSession.commit(); call(request.setType(NOTIF_NEW_QUALITY_GATE_STATUS).setChannel(twitterChannel.getKey())); db.notifications().assertDoesNotExist(twitterChannel.getKey(), NOTIF_NEW_QUALITY_GATE_STATUS, user.getUuid(), null); } @Test public void remove_a_project_notification() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); dbSession.commit(); call(request.setProject(project.getKey())); db.notifications().assertDoesNotExist(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user.getUuid(), project); } @Test public void fail_when_remove_a_global_notification_when_a_project_one_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, project); dbSession.commit(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Notification doesn't exist"); } @Test public void fail_when_remove_a_project_notification_when_a_global_one_exists() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); RemoveRequest request = this.request.setProject(project.getKey()); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Notification doesn't exist"); } @Test public void http_no_content() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); TestResponse result = call(request); assertThat(result.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void remove_a_notification_from_a_user_as_system_administrator() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); db.notifications().assertExists(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user.getUuid(), null); userSession.logIn().setSystemAdministrator(); dbSession.commit(); call(request.setLogin(user.getLogin())); db.notifications().assertDoesNotExist(defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user.getUuid(), null); } @Test public void fail_if_login_is_provided_and_unknown() { UserDto user = db.users().insertUser(); userSession.logIn(user).setSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); RemoveRequest request = this.request.setLogin("LOGIN 404"); assertThatThrownBy(() -> call(request)) .isInstanceOf(NotFoundException.class) .hasMessage("User 'LOGIN 404' not found"); } @Test public void fail_if_login_provided_and_not_system_administrator() { UserDto user = db.users().insertUser(); userSession.logIn(user).setNonSystemAdministrator(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); notificationUpdater.add(dbSession, defaultChannel.getKey(), NOTIF_MY_NEW_ISSUES, user, null); dbSession.commit(); RemoveRequest request = this.request.setLogin(user.getLogin()); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_notification_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Notification doesn't exist"); } @Test public void fail_when_unknown_channel() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); RemoveRequest request = this.request.setChannel("Channel42"); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_unknown_global_dispatcher() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); RemoveRequest request = this.request.setType("Dispatcher42"); assertThatThrownBy(() -> call(request)) .isInstanceOf(BadRequestException.class) .hasMessage("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher2, Dispatcher3]"); } @Test public void fail_when_unknown_project_dispatcher() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(asList(NOTIF_MY_NEW_ISSUES, NOTIF_NEW_QUALITY_GATE_STATUS)); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); RemoveRequest request = this.request.setType("Dispatcher42").setProject(project.getKey()); assertThatThrownBy(() -> call(request)) .isInstanceOf(BadRequestException.class) .hasMessage("Value of parameter 'type' (Dispatcher42) must be one of: [Dispatcher1, Dispatcher3]"); } @Test public void fail_when_no_type_parameter() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'type' parameter is missing"); } @Test public void fail_when_project_is_unknown() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); RemoveRequest request = this.request.setProject("Project-42"); assertThatThrownBy(() -> call(request)) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_component_is_not_a_project() { UserDto user = db.users().insertUser(); userSession.logIn(user); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); db.components().insertPortfolioAndSnapshot(newPortfolio().setKey("VIEW_1")); RemoveRequest request = this.request.setProject("VIEW_1"); assertThatThrownBy(() -> call(request)) .isInstanceOf(NotFoundException.class) .hasMessage("Project 'VIEW_1' not found"); } @Test public void fail_when_not_authenticated() { userSession.anonymous(); when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES)); assertThatThrownBy(() -> call(request)) .isInstanceOf(UnauthorizedException.class); } private TestResponse call(RemoveRequest remove) { TestRequest request = ws.newRequest(); request.setParam(PARAM_TYPE, remove.getType()); ofNullable(remove.getChannel()).ifPresent(channel -> request.setParam(PARAM_CHANNEL, channel)); ofNullable(remove.getProject()).ifPresent(project -> request.setParam(PARAM_PROJECT, project)); ofNullable(remove.getLogin()).ifPresent(login -> request.setParam(PARAM_LOGIN, login)); return request.execute(); } private static class FakeNotificationChannel extends NotificationChannel { private final String key; private FakeNotificationChannel(String key) { this.key = key; } @Override public String getKey() { return this.key; } @Override public boolean deliver(Notification notification, String username) { // do nothing return true; } } }
14,268
41.978916
167
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/DefaultTemplatesResolverImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; public class DefaultTemplatesResolverImplIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private ResourceTypesRule resourceTypesWithPortfoliosInstalled = new ResourceTypesRule().setRootQualifiers(PROJECT, APP, VIEW); private ResourceTypesRule resourceTypesWithApplicationInstalled = new ResourceTypesRule().setRootQualifiers(PROJECT, APP); private ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT); private DefaultTemplatesResolverImpl underTestWithPortfoliosInstalled = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypesWithPortfoliosInstalled); private DefaultTemplatesResolverImpl underTestWithApplicationInstalled = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypesWithApplicationInstalled); private DefaultTemplatesResolverImpl underTest = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypes); @Test public void get_default_templates_when_portfolio_not_installed() { db.permissionTemplates().setDefaultTemplates("prj", null, null); assertThat(underTest.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTest.resolve(db.getSession()).getApplication()).isEmpty(); assertThat(underTest.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test public void get_default_templates_always_return_project_template_even_when_all_templates_are_defined_but_portfolio_not_installed() { db.permissionTemplates().setDefaultTemplates("prj", "app", "port"); assertThat(underTest.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTest.resolve(db.getSession()).getApplication()).isEmpty(); assertThat(underTest.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test public void get_default_templates_always_return_project_template_when_only_project_template_and_portfolio_is_installed_() { db.permissionTemplates().setDefaultTemplates("prj", null, null); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getApplication()).contains("prj"); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getPortfolio()).contains("prj"); } @Test public void get_default_templates_for_all_components_when_portfolio_is_installed() { db.permissionTemplates().setDefaultTemplates("prj", "app", "port"); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getApplication()).contains("app"); assertThat(underTestWithPortfoliosInstalled.resolve(db.getSession()).getPortfolio()).contains("port"); } @Test public void get_default_templates_always_return_project_template_when_only_project_template_and_application_is_installed_() { db.permissionTemplates().setDefaultTemplates("prj", null, null); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getApplication()).contains("prj"); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test public void get_default_templates_for_all_components_when_application_is_installed() { db.permissionTemplates().setDefaultTemplates("prj", "app", null); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getProject()).contains("prj"); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getApplication()).contains("app"); assertThat(underTestWithApplicationInstalled.resolve(db.getSession()).getPortfolio()).isEmpty(); } @Test public void fail_when_default_template_for_project_is_missing() { DbSession session = db.getSession(); assertThatThrownBy(() -> underTestWithPortfoliosInstalled.resolve(session)) .isInstanceOf(IllegalStateException.class) .hasMessage("Default template for project is missing"); } }
5,476
48.342342
165
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/GroupPermissionChangerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.Uuids; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.GroupPermissionDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; public class GroupPermissionChangerIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final GroupPermissionChanger underTest = new GroupPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); private GroupDto group; private ProjectDto privateProject; private ProjectDto publicProject; @Before public void setUp() { group = db.users().insertGroup("a-group"); privateProject = db.components().insertPrivateProject().getProjectDto(); publicProject = db.components().insertPublicProject().getProjectDto(); } @Test public void apply_adds_global_permission_to_group() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, ADMINISTER_QUALITY_PROFILES.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly(ADMINISTER_QUALITY_PROFILES.getKey()); } @Test public void apply_adds_global_permission_to_group_AnyOne() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, ADMINISTER_QUALITY_PROFILES.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(null)).containsOnly(ADMINISTER_QUALITY_PROFILES.getKey()); } @Test public void apply_fails_with_BadRequestException_when_adding_any_permission_to_group_AnyOne_on_private_project() { GroupUuidOrAnyone anyOneGroup = GroupUuidOrAnyone.forAnyone(); permissionService.getAllProjectPermissions() .forEach(perm -> { GroupPermissionChange change = new GroupPermissionChange(PermissionChange.Operation.ADD, perm, privateProject, anyOneGroup, permissionService); try { apply(change); fail("a BadRequestException should have been thrown"); } catch (BadRequestException e) { assertThat(e).hasMessage("No permission can be granted to Anyone on a private component"); } }); } @Test public void apply_has_no_effect_when_removing_any_permission_to_group_AnyOne_on_private_project() { permissionService.getAllProjectPermissions() .forEach(this::unsafeInsertProjectPermissionOnAnyone); GroupUuidOrAnyone anyOneGroup = GroupUuidOrAnyone.forAnyone(); permissionService.getAllProjectPermissions() .forEach(perm -> { apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, perm, privateProject, anyOneGroup, permissionService)); assertThat(db.users().selectAnyonePermissions(privateProject.getUuid())).contains(perm); }); } @Test public void apply_adds_permission_USER_to_group_on_private_project() { applyAddsPermissionToGroupOnPrivateProject(UserRole.USER); } @Test public void apply_adds_permission_CODEVIEWER_to_group_on_private_project() { applyAddsPermissionToGroupOnPrivateProject(UserRole.CODEVIEWER); } @Test public void apply_adds_permission_ADMIN_to_group_on_private_project() { applyAddsPermissionToGroupOnPrivateProject(UserRole.ADMIN); } @Test public void apply_adds_permission_ISSUE_ADMIN_to_group_on_private_project() { applyAddsPermissionToGroupOnPrivateProject(UserRole.ISSUE_ADMIN); } @Test public void apply_adds_permission_SCAN_EXECUTION_to_group_on_private_project() { applyAddsPermissionToGroupOnPrivateProject(GlobalPermission.SCAN.getKey()); } private void applyAddsPermissionToGroupOnPrivateProject(String permission) { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(permission); } @Test public void apply_removes_permission_USER_from_group_on_private_project() { applyRemovesPermissionFromGroupOnPrivateProject(UserRole.USER); } @Test public void apply_removes_permission_CODEVIEWER_from_group_on_private_project() { applyRemovesPermissionFromGroupOnPrivateProject(UserRole.CODEVIEWER); } @Test public void apply_removes_permission_ADMIN_from_on_private_project() { applyRemovesPermissionFromGroupOnPrivateProject(UserRole.ADMIN); } @Test public void apply_removes_permission_ISSUE_ADMIN_from_on_private_project() { applyRemovesPermissionFromGroupOnPrivateProject(UserRole.ISSUE_ADMIN); } @Test public void apply_removes_permission_SCAN_EXECUTION_from_on_private_project() { applyRemovesPermissionFromGroupOnPrivateProject(GlobalPermission.SCAN.getKey()); } private void applyRemovesPermissionFromGroupOnPrivateProject(String permission) { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertEntityPermissionOnGroup(group, permission, privateProject); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, permission, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(permission); } @Test public void apply_has_no_effect_when_adding_USER_permission_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.USER, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject.getUuid())).isEmpty(); } @Test public void apply_has_no_effect_when_adding_CODEVIEWER_permission_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject.getUuid())).isEmpty(); } @Test public void apply_fails_with_BadRequestException_when_adding_permission_ADMIN_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ADMIN, publicProject, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("It is not possible to add the 'admin' permission to group 'Anyone'."); } @Test public void apply_adds_permission_ISSUE_ADMIN_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, UserRole.ISSUE_ADMIN, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void apply_adds_permission_SCAN_EXECUTION_to_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, GlobalPermission.SCAN.getKey(), publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject.getUuid())).containsOnly(GlobalPermission.SCAN.getKey()); } @Test public void apply_fails_with_BadRequestException_when_removing_USER_permission_from_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_CODEVIEWER_permission_from_group_AnyOne_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void apply_removes_ADMIN_permission_from_group_AnyOne_on_a_public_project() { applyRemovesPermissionFromGroupAnyOneOnAPublicProject(UserRole.ADMIN); } @Test public void apply_removes_ISSUE_ADMIN_permission_from_group_AnyOne_on_a_public_project() { applyRemovesPermissionFromGroupAnyOneOnAPublicProject(UserRole.ISSUE_ADMIN); } @Test public void apply_removes_SCAN_EXECUTION_permission_from_group_AnyOne_on_a_public_project() { applyRemovesPermissionFromGroupAnyOneOnAPublicProject(GlobalPermission.SCAN.getKey()); } private void applyRemovesPermissionFromGroupAnyOneOnAPublicProject(String permission) { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); db.users().insertEntityPermissionOnAnyone(permission, publicProject); apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, permission, publicProject, groupUuid, permissionService)); assertThat(db.users().selectAnyonePermissions(publicProject.getUuid())).isEmpty(); } @Test public void apply_fails_with_BadRequestException_when_removing_USER_permission_from_a_group_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.USER, publicProject, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_CODEVIEWER_permission_from_a_group_on_a_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); assertThatThrownBy(() -> apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.CODEVIEWER, publicProject, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void add_permission_to_anyone() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.forAnyone(); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, ADMINISTER_QUALITY_PROFILES.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectAnyonePermissions(null)).containsOnly(ADMINISTER_QUALITY_PROFILES.getKey()); } @Test public void do_nothing_when_adding_permission_that_already_exists() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER_QUALITY_GATES); apply(new GroupPermissionChange(PermissionChange.Operation.ADD, ADMINISTER_QUALITY_GATES.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly(ADMINISTER_QUALITY_GATES.getKey()); } @Test public void fail_to_add_global_permission_but_SCAN_and_ADMIN_on_private_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); permissionService.getGlobalPermissions().stream() .map(GlobalPermission::getKey) .filter(perm -> !UserRole.ADMIN.equals(perm) && !GlobalPermission.SCAN.getKey().equals(perm)) .forEach(perm -> { try { new GroupPermissionChange(PermissionChange.Operation.ADD, perm, privateProject, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + perm); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid project permission '" + perm + "'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); } }); } @Test public void fail_to_add_global_permission_but_SCAN_and_ADMIN_on_public_project() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); permissionService.getGlobalPermissions().stream() .map(GlobalPermission::getKey) .filter(perm -> !UserRole.ADMIN.equals(perm) && !GlobalPermission.SCAN.getKey().equals(perm)) .forEach(perm -> { try { new GroupPermissionChange(PermissionChange.Operation.ADD, perm, publicProject, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + perm); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid project permission '" + perm + "'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); } }); } @Test public void fail_to_add_project_permission_but_SCAN_and_ADMIN_on_global_group() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); permissionService.getAllProjectPermissions() .stream() .filter(perm -> !GlobalPermission.SCAN.getKey().equals(perm) && !GlobalPermission.ADMINISTER.getKey().equals(perm)) .forEach(permission -> { try { new GroupPermissionChange(PermissionChange.Operation.ADD, permission, null, groupUuid, permissionService); fail("a BadRequestException should have been thrown for permission " + permission); } catch (BadRequestException e) { assertThat(e).hasMessage("Invalid global permission '" + permission + "'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); } }); } @Test public void remove_permission_from_group() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER_QUALITY_GATES); db.users().insertPermissionOnGroup(group, PROVISION_PROJECTS); apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, ADMINISTER_QUALITY_GATES.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly(PROVISION_PROJECTS.getKey()); } @Test public void remove_project_permission_from_group() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER_QUALITY_GATES); db.users().insertEntityPermissionOnGroup(group, UserRole.ISSUE_ADMIN, privateProject); db.users().insertEntityPermissionOnGroup(group, UserRole.CODEVIEWER, privateProject); apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly(ADMINISTER_QUALITY_GATES.getKey()); assertThat(db.users().selectGroupPermissions(group, privateProject)).containsOnly(UserRole.CODEVIEWER); } @Test public void do_not_fail_if_removing_a_permission_that_does_not_exist() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, UserRole.ISSUE_ADMIN, privateProject, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, privateProject)).isEmpty(); } @Test public void fail_to_remove_admin_permission_if_no_more_admins() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER); assertThatThrownBy(() -> underTest.apply(db.getSession(), new GroupPermissionChange(PermissionChange.Operation.REMOVE, ADMINISTER.getKey(), null, groupUuid, permissionService))) .isInstanceOf(BadRequestException.class) .hasMessage("Last group with permission 'admin'. Permission cannot be removed."); } @Test public void remove_admin_group_if_still_other_admins() { GroupUuidOrAnyone groupUuid = GroupUuidOrAnyone.from(group); db.users().insertPermissionOnGroup(group, ADMINISTER); UserDto admin = db.users().insertUser(); db.users().insertGlobalPermissionOnUser(admin, ADMINISTER); apply(new GroupPermissionChange(PermissionChange.Operation.REMOVE, ADMINISTER.getKey(), null, groupUuid, permissionService)); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); } private void apply(GroupPermissionChange change) { underTest.apply(db.getSession(), change); db.commit(); } private void unsafeInsertProjectPermissionOnAnyone(String perm) { GroupPermissionDto dto = new GroupPermissionDto() .setUuid(Uuids.createFast()) .setGroupUuid(null) .setRole(perm) .setEntityUuid(privateProject.getUuid()) .setEntityName(privateProject.getName()); db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, privateProject, null); db.commit(); } }
19,377
43.64977
181
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/PermissionTemplateServiceIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.template.PermissionTemplateDbTester; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.Indexers; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.TemplateMatchingKeyException; import org.sonar.server.tester.UserSessionRule; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; public class PermissionTemplateServiceIT { @Rule public DbTester dbTester = DbTester.create(); private final ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); private final DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbTester.getDbClient(), resourceTypesRule); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypesRule); private final UserSessionRule userSession = UserSessionRule.standalone(); private final PermissionTemplateDbTester templateDb = dbTester.permissionTemplates(); private final DbSession session = dbTester.getSession(); private final Indexers indexers = new TestIndexers(); private final PermissionTemplateService underTest = new PermissionTemplateService(dbTester.getDbClient(), indexers, userSession, defaultTemplatesResolver, new SequenceUuidFactory()); @Test public void apply_does_not_insert_permission_to_group_AnyOne_when_applying_template_on_private_project() { ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(privateProject)); assertThat(selectProjectPermissionsOfGroup(null, privateProject.getUuid())).isEmpty(); } @Test public void apply_default_does_not_insert_permission_to_group_AnyOne_when_applying_template_on_private_project() { ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); UserDto creator = dbTester.users().insertUser(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, privateProject, creator.getUuid()); assertThat(selectProjectPermissionsOfGroup(null, privateProject.getUuid())).isEmpty(); } @Test public void apply_inserts_permissions_to_group_AnyOne_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(publicProject)); assertThat(selectProjectPermissionsOfGroup(null, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_permissions_to_group_AnyOne_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, publicProject, null); assertThat(selectProjectPermissionsOfGroup(null, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void apply_inserts_any_permissions_to_group_when_applying_template_on_private_project() { ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); GroupDto group = dbTester.users().insertGroup(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(privateProject)); assertThat(selectProjectPermissionsOfGroup(group, privateProject.getUuid())) .containsOnly("p1", UserRole.CODEVIEWER, UserRole.USER, UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_any_permissions_to_group_when_applying_template_on_private_project() { GroupDto group = dbTester.users().insertGroup(); ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, privateProject, null); assertThat(selectProjectPermissionsOfGroup(group, privateProject.getUuid())) .containsOnly("p1", UserRole.CODEVIEWER, UserRole.USER, UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void apply_inserts_permissions_to_group_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); GroupDto group = dbTester.users().insertGroup(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(publicProject)); assertThat(selectProjectPermissionsOfGroup(group, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_permissions_to_group_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); GroupDto group = dbTester.users().insertGroup(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, perm)); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, publicProject, null); assertThat(selectProjectPermissionsOfGroup(group, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void apply_inserts_permissions_to_user_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(publicProject)); assertThat(selectProjectPermissionsOfUser(user, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_permissions_to_user_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, publicProject, null); assertThat(selectProjectPermissionsOfUser(user, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void apply_inserts_any_permissions_to_user_when_applying_template_on_private_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); underTest.applyAndCommit(session, permissionTemplate, singletonList(privateProject)); assertThat(selectProjectPermissionsOfUser(user, privateProject.getUuid())) .containsOnly("p1", UserRole.CODEVIEWER, UserRole.USER, UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_any_permissions_to_user_when_applying_template_on_private_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, perm)); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, privateProject, null); assertThat(selectProjectPermissionsOfUser(user, privateProject.getUuid())) .containsOnly("p1", UserRole.CODEVIEWER, UserRole.USER, UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_permissions_to_ProjectCreator_but_USER_and_CODEVIEWER_when_applying_template_on_public_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto publicProject = dbTester.components().insertPublicProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, publicProject, user.getUuid()); assertThat(selectProjectPermissionsOfUser(user, publicProject.getUuid())) .containsOnly("p1", UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void applyDefault_inserts_any_permissions_to_ProjectCreator_when_applying_template_on_private_project() { PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); ProjectDto privateProject = dbTester.components().insertPrivateProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); permissionService.getAllProjectPermissions() .forEach(perm -> dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, perm)); dbTester.permissionTemplates().addProjectCreatorToTemplate(permissionTemplate, "p1"); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, privateProject, user.getUuid()); assertThat(selectProjectPermissionsOfUser(user, privateProject.getUuid())) .containsOnly("p1", UserRole.CODEVIEWER, UserRole.USER, UserRole.ADMIN, UserRole.ISSUE_ADMIN, UserRole.SECURITYHOTSPOT_ADMIN, GlobalPermission.SCAN.getKey()); } @Test public void apply_template_on_view() { PortfolioDto portfolio = dbTester.components().insertPrivatePortfolioDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, portfolio, null); assertThat(selectProjectPermissionsOfGroup(group, portfolio.getUuid())) .containsOnly(GlobalPermission.ADMINISTER.getKey(), GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_default_template_on_application() { ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); PermissionTemplateDto appPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, appPermissionTemplate, null); underTest.applyDefaultToNewComponent(session, application, null); assertThat(selectProjectPermissionsOfGroup(group, application.getUuid())) .containsOnly(GlobalPermission.ADMINISTER.getKey(), GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_default_template_on_portfolio() { PortfolioDto portfolio = dbTester.components().insertPublicPortfolioDto(); PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); PermissionTemplateDto portPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(portPermissionTemplate, group, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(portPermissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, portPermissionTemplate); underTest.applyDefaultToNewComponent(session, portfolio, null); assertThat(selectProjectPermissionsOfGroup(group, portfolio.getUuid())) .containsOnly(GlobalPermission.ADMINISTER.getKey(), GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_project_default_template_on_view_when_no_view_default_template() { PortfolioDto portfolio = dbTester.components().insertPrivatePortfolioDto(); PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(projectPermissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, portfolio, null); assertThat(selectProjectPermissionsOfGroup(group, portfolio.getUuid())).containsOnly(GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_template_on_applications() { ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(permissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, application, null); assertThat(selectProjectPermissionsOfGroup(group, application.getUuid())) .containsOnly(GlobalPermission.ADMINISTER.getKey(), GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_default_view_template_on_application() { ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); PermissionTemplateDto appPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); PermissionTemplateDto portPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(appPermissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, appPermissionTemplate, portPermissionTemplate); underTest.applyDefaultToNewComponent(session, application, null); assertThat(selectProjectPermissionsOfGroup(group, application.getUuid())) .containsOnly(GlobalPermission.ADMINISTER.getKey(), GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_project_default_template_on_application_when_no_application_default_template() { ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); PermissionTemplateDto projectPermissionTemplate = dbTester.permissionTemplates().insertTemplate(); GroupDto group = dbTester.users().insertGroup(); dbTester.permissionTemplates().addGroupToTemplate(projectPermissionTemplate, group, GlobalPermission.PROVISION_PROJECTS.getKey()); dbTester.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, null); underTest.applyDefaultToNewComponent(session, application, null); assertThat(selectProjectPermissionsOfGroup(group, application.getUuid())).containsOnly(GlobalPermission.PROVISION_PROJECTS.getKey()); } @Test public void apply_permission_template() { UserDto user = dbTester.users().insertUser(); ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto(); GroupDto adminGroup = dbTester.users().insertGroup(); GroupDto userGroup = dbTester.users().insertGroup(); dbTester.users().insertPermissionOnGroup(adminGroup, GlobalPermission.ADMINISTER.getKey()); dbTester.users().insertPermissionOnGroup(userGroup, UserRole.USER); dbTester.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER); PermissionTemplateDto permissionTemplate = dbTester.permissionTemplates().insertTemplate(); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, adminGroup, GlobalPermission.ADMINISTER.getKey()); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, adminGroup, UserRole.ISSUE_ADMIN); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, userGroup, UserRole.USER); dbTester.permissionTemplates().addGroupToTemplate(permissionTemplate, userGroup, UserRole.CODEVIEWER); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, UserRole.USER); dbTester.permissionTemplates().addAnyoneToTemplate(permissionTemplate, UserRole.CODEVIEWER); dbTester.permissionTemplates().addUserToTemplate(permissionTemplate, user, GlobalPermission.ADMINISTER.getKey()); assertThat(selectProjectPermissionsOfGroup(adminGroup, project.getUuid())).isEmpty(); assertThat(selectProjectPermissionsOfGroup(userGroup, project.getUuid())).isEmpty(); assertThat(selectProjectPermissionsOfGroup(null, project.getUuid())).isEmpty(); assertThat(selectProjectPermissionsOfUser(user, project.getUuid())).isEmpty(); underTest.applyAndCommit(session, permissionTemplate, singletonList(project)); assertThat(selectProjectPermissionsOfGroup(adminGroup, project.getUuid())).containsOnly(GlobalPermission.ADMINISTER.getKey(), UserRole.ISSUE_ADMIN); assertThat(selectProjectPermissionsOfGroup(userGroup, project.getUuid())).containsOnly(UserRole.USER, UserRole.CODEVIEWER); assertThat(selectProjectPermissionsOfGroup(null, project.getUuid())).isEmpty(); assertThat(selectProjectPermissionsOfUser(user, project.getUuid())).containsOnly(GlobalPermission.ADMINISTER.getKey()); } private List<String> selectProjectPermissionsOfGroup(@Nullable GroupDto groupDto, String projectUuid) { return dbTester.getDbClient().groupPermissionDao().selectEntityPermissionsOfGroup(session, groupDto != null ? groupDto.getUuid() : null, projectUuid); } private List<String> selectProjectPermissionsOfUser(UserDto userDto, String projectUuid) { return dbTester.getDbClient().userPermissionDao().selectEntityPermissionsOfUser(session, userDto.getUuid(), projectUuid); } @Test public void would_user_have_scan_permission_with_default_permission_template() { GroupDto group = dbTester.users().insertGroup(); UserDto user = dbTester.users().insertUser(); dbTester.users().insertMember(group, user); PermissionTemplateDto template = templateDb.insertTemplate(); dbTester.permissionTemplates().setDefaultTemplates(template, null, null); templateDb.addProjectCreatorToTemplate(template.getUuid(), GlobalPermission.SCAN.getKey(), template.getName()); templateDb.addUserToTemplate(template.getUuid(), user.getUuid(), UserRole.USER, template.getName(), user.getLogin()); templateDb.addGroupToTemplate(template.getUuid(), group.getUuid(), UserRole.CODEVIEWER, template.getName(), group.getName()); templateDb.addGroupToTemplate(template.getUuid(), null, UserRole.ISSUE_ADMIN, template.getName(), null); // authenticated user checkWouldUserHaveScanPermission(user.getUuid(), true); // anonymous user checkWouldUserHaveScanPermission(null, false); } @Test public void would_user_have_scan_permission_with_unknown_default_permission_template() { dbTester.permissionTemplates().setDefaultTemplates("UNKNOWN_TEMPLATE_UUID", null, null); checkWouldUserHaveScanPermission(null, false); } @Test public void would_user_have_scan_permission_with_empty_template() { PermissionTemplateDto template = templateDb.insertTemplate(); dbTester.permissionTemplates().setDefaultTemplates(template, null, null); checkWouldUserHaveScanPermission(null, false); } @Test public void apply_permission_template_with_key_pattern_collision() { final String key = "hi-test"; final String keyPattern = ".*-test"; Stream<PermissionTemplateDto> templates = Stream.of( templateDb.insertTemplate(t -> t.setKeyPattern(keyPattern)), templateDb.insertTemplate(t -> t.setKeyPattern(keyPattern)) ); String templateNames = templates .map(PermissionTemplateDto::getName) .sorted(String.CASE_INSENSITIVE_ORDER) .map(x -> String.format("\"%s\"", x)) .collect(Collectors.joining(", ")); ProjectDto project = dbTester.components().insertPrivateProject(p -> p.setKey(key)).getProjectDto(); assertThatThrownBy(() -> underTest.applyDefaultToNewComponent(session, project, null)) .isInstanceOf(TemplateMatchingKeyException.class) .hasMessageContaining("The \"%s\" key matches multiple permission templates: %s.", key, templateNames); } private void checkWouldUserHaveScanPermission(@Nullable String userUuid, boolean expectedResult) { assertThat(underTest.wouldUserHaveScanPermissionWithDefaultTemplate(session, userUuid, "PROJECT_KEY")) .isEqualTo(expectedResult); } }
27,999
56.971014
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/UserPermissionChangerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserIdDto; import org.sonar.server.exceptions.BadRequestException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.permission.PermissionChange.Operation.ADD; import static org.sonar.server.permission.PermissionChange.Operation.REMOVE; public class UserPermissionChangerIT { @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final UserPermissionChanger underTest = new UserPermissionChanger(db.getDbClient(), new SequenceUuidFactory()); private UserDto user1; private UserDto user2; private EntityDto privateProject; private EntityDto publicProject; @Before public void setUp() { user1 = db.users().insertUser(); user2 = db.users().insertUser(); privateProject = db.components().insertPrivateProject().getProjectDto(); publicProject = db.components().insertPublicProject().getProjectDto(); } @Test public void apply_adds_any_global_permission_to_user() { permissionService.getGlobalPermissions() .forEach(perm -> { UserPermissionChange change = new UserPermissionChange(ADD, perm.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).contains(perm); }); } @Test public void apply_removes_any_global_permission_to_user() { // give ADMIN perm to user2 so that user1 is not the only one with this permission and it can be removed from user1 db.users().insertGlobalPermissionOnUser(user2, GlobalPermission.ADMINISTER); permissionService.getGlobalPermissions() .forEach(perm -> db.users().insertGlobalPermissionOnUser(user1, perm)); assertThat(db.users().selectPermissionsOfUser(user1)) .containsOnly(permissionService.getGlobalPermissions().toArray(new GlobalPermission[0])); permissionService.getGlobalPermissions() .forEach(perm -> { UserPermissionChange change = new UserPermissionChange(REMOVE, perm.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).doesNotContain(perm); }); } @Test public void apply_has_no_effect_when_adding_permission_USER_on_a_public_project() { UserPermissionChange change = new UserPermissionChange(ADD, UserRole.USER, publicProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, publicProject.getUuid())).doesNotContain(UserRole.USER); } @Test public void apply_has_no_effect_when_adding_permission_CODEVIEWER_on_a_public_project() { UserPermissionChange change = new UserPermissionChange(ADD, UserRole.CODEVIEWER, publicProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, publicProject.getUuid())).doesNotContain(UserRole.CODEVIEWER); } @Test public void apply_adds_permission_ADMIN_on_a_public_project() { applyAddsPermissionOnAPublicProject(UserRole.ADMIN); } @Test public void apply_adds_permission_ISSUE_ADMIN_on_a_public_project() { applyAddsPermissionOnAPublicProject(UserRole.ISSUE_ADMIN); } @Test public void apply_adds_permission_SCAN_EXECUTION_on_a_public_project() { applyAddsPermissionOnAPublicProject(GlobalPermission.SCAN.getKey()); } private void applyAddsPermissionOnAPublicProject(String permission) { UserPermissionChange change = new UserPermissionChange(ADD, permission, publicProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, publicProject.getUuid())).containsOnly(permission); } @Test public void apply_fails_with_BadRequestException_when_removing_permission_USER_from_a_public_project() { UserPermissionChange change = new UserPermissionChange(REMOVE, UserRole.USER, publicProject, UserIdDto.from(user1), permissionService); assertThatThrownBy(() -> apply(change)) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void apply_fails_with_BadRequestException_when_removing_permission_CODEVIEWER_from_a_public_project() { UserPermissionChange change = new UserPermissionChange(REMOVE, UserRole.CODEVIEWER, publicProject, UserIdDto.from(user1), permissionService); assertThatThrownBy(() -> apply(change)) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void apply_removes_permission_ADMIN_from_a_public_project() { applyRemovesPermissionFromPublicProject(UserRole.ADMIN); } @Test public void apply_removes_permission_ISSUE_ADMIN_from_a_public_project() { applyRemovesPermissionFromPublicProject(UserRole.ISSUE_ADMIN); } @Test public void apply_removes_permission_SCAN_EXECUTION_from_a_public_project() { applyRemovesPermissionFromPublicProject(GlobalPermission.SCAN.getKey()); } private void applyRemovesPermissionFromPublicProject(String permission) { db.users().insertProjectPermissionOnUser(user1, permission, publicProject); UserPermissionChange change = new UserPermissionChange(REMOVE, permission, publicProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, publicProject.getUuid())).isEmpty(); } @Test public void apply_adds_any_permission_to_a_private_project() { permissionService.getAllProjectPermissions() .forEach(permission -> { UserPermissionChange change = new UserPermissionChange(ADD, permission, privateProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).contains(permission); }); } @Test public void apply_removes_any_permission_from_a_private_project() { permissionService.getAllProjectPermissions() .forEach(permission -> db.users().insertProjectPermissionOnUser(user1, permission, privateProject)); permissionService.getAllProjectPermissions() .forEach(permission -> { UserPermissionChange change = new UserPermissionChange(REMOVE, permission, privateProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).doesNotContain(permission); }); } @Test public void add_global_permission_to_user() { UserPermissionChange change = new UserPermissionChange(ADD, GlobalPermission.SCAN.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).containsOnly(GlobalPermission.SCAN); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).isEmpty(); assertThat(db.users().selectPermissionsOfUser(user2)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user2, privateProject.getUuid())).isEmpty(); } @Test public void add_project_permission_to_user() { UserPermissionChange change = new UserPermissionChange(ADD, UserRole.ISSUE_ADMIN, privateProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).contains(UserRole.ISSUE_ADMIN); assertThat(db.users().selectPermissionsOfUser(user2)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user2, privateProject.getUuid())).isEmpty(); } @Test public void do_nothing_when_adding_global_permission_that_already_exists() { db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER_QUALITY_GATES); UserPermissionChange change = new UserPermissionChange(ADD, GlobalPermission.ADMINISTER_QUALITY_GATES.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).containsOnly(GlobalPermission.ADMINISTER_QUALITY_GATES); } @Test public void fail_to_add_global_permission_on_project() { assertThatThrownBy(() -> { UserPermissionChange change = new UserPermissionChange(ADD, GlobalPermission.ADMINISTER_QUALITY_GATES.getKey(), privateProject, UserIdDto.from(user1), permissionService); apply(change); }) .isInstanceOf(BadRequestException.class) .hasMessage("Invalid project permission 'gateadmin'. Valid values are [" + StringUtils.join(permissionService.getAllProjectPermissions(), ", ") + "]"); } @Test public void fail_to_add_project_permission() { assertThatThrownBy(() -> { UserPermissionChange change = new UserPermissionChange(ADD, UserRole.ISSUE_ADMIN, null, UserIdDto.from(user1), permissionService); apply(change); }) .isInstanceOf(BadRequestException.class) .hasMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); } @Test public void remove_global_permission_from_user() { db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER_QUALITY_GATES); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.SCAN); db.users().insertGlobalPermissionOnUser(user2, GlobalPermission.ADMINISTER_QUALITY_GATES); db.users().insertProjectPermissionOnUser(user1, UserRole.ISSUE_ADMIN, privateProject); UserPermissionChange change = new UserPermissionChange(REMOVE, GlobalPermission.ADMINISTER_QUALITY_GATES.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).containsOnly(GlobalPermission.SCAN); assertThat(db.users().selectPermissionsOfUser(user2)).containsOnly(GlobalPermission.ADMINISTER_QUALITY_GATES); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void remove_project_permission_from_user() { EntityDto project2 = db.components().insertPrivateProject().getProjectDto(); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER_QUALITY_GATES); db.users().insertProjectPermissionOnUser(user1, UserRole.ISSUE_ADMIN, privateProject); db.users().insertProjectPermissionOnUser(user1, UserRole.USER, privateProject); db.users().insertProjectPermissionOnUser(user2, UserRole.ISSUE_ADMIN, privateProject); db.users().insertProjectPermissionOnUser(user1, UserRole.ISSUE_ADMIN, project2); UserPermissionChange change = new UserPermissionChange(REMOVE, UserRole.ISSUE_ADMIN, privateProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).containsOnly(UserRole.USER); assertThat(db.users().selectEntityPermissionOfUser(user2, privateProject.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); assertThat(db.users().selectEntityPermissionOfUser(user1, project2.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void do_not_fail_if_removing_a_global_permission_that_does_not_exist() { UserPermissionChange change = new UserPermissionChange(REMOVE, GlobalPermission.ADMINISTER_QUALITY_GATES.getKey(), null, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectPermissionsOfUser(user1)).isEmpty(); } @Test public void do_not_fail_if_removing_a_project_permission_that_does_not_exist() { UserPermissionChange change = new UserPermissionChange(REMOVE, UserRole.ISSUE_ADMIN, privateProject, UserIdDto.from(user1), permissionService); apply(change); assertThat(db.users().selectEntityPermissionOfUser(user1, privateProject.getUuid())).isEmpty(); } @Test public void fail_to_remove_admin_global_permission_if_no_more_admins() { db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER); assertThatThrownBy(() -> { UserPermissionChange change = new UserPermissionChange(REMOVE, GlobalPermission.ADMINISTER.getKey(), null, UserIdDto.from(user1), permissionService); underTest.apply(db.getSession(), change); }) .isInstanceOf(BadRequestException.class) .hasMessage("Last user with permission 'admin'. Permission cannot be removed."); } @Test public void remove_admin_user_if_still_other_admins() { db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER); GroupDto admins = db.users().insertGroup("admins"); db.users().insertMember(admins, user2); db.users().insertPermissionOnGroup(admins, GlobalPermission.ADMINISTER); UserPermissionChange change = new UserPermissionChange(REMOVE, GlobalPermission.ADMINISTER.getKey(), null, UserIdDto.from(user1), permissionService); underTest.apply(db.getSession(), change); assertThat(db.users().selectPermissionsOfUser(user1)).isEmpty(); } private void apply(UserPermissionChange change) { underTest.apply(db.getSession(), change); db.commit(); } }
14,959
43.260355
176
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/AddGroupActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; public class AddGroupActionIT extends BasePermissionWsIT<AddGroupAction> { private static final String A_PROJECT_UUID = "project-uuid"; private static final String A_PROJECT_KEY = "project-key"; private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); @Override protected AddGroupAction buildWsAction() { return new AddGroupAction(db.getDbClient(), userSession, newPermissionUpdater(), newPermissionWsSupport(), wsParameters, permissionService); } @Test public void verify_definition() { Action wsDef = wsTester.getDef(); assertThat(wsDef.isInternal()).isFalse(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isTrue(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly( tuple("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."), tuple("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead.")); } @Test public void add_permission_to_group_referenced_by_its_name() { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, "sonar-administrators") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly("admin"); } @Test public void reference_group_by_its_name() { GroupDto group = db.users().insertGroup("the-group"); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(group, null)).containsOnly("provisioning"); } @Test public void add_permission_to_project_referenced_by_its_id() { GroupDto group = db.users().insertGroup("sonar-administrators"); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, project)).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void add_permission_to_project_referenced_by_its_key() { GroupDto group = db.users().insertGroup("sonar-administrators"); ProjectDto project = db.components().insertPrivateProject(A_PROJECT_UUID, c -> c.setKey(A_PROJECT_KEY)).getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_KEY, A_PROJECT_KEY) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, project)).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void add_with_portfolio_uuid() { GroupDto group = db.users().insertGroup("sonar-administrators"); PortfolioDto portfolio = db.components().insertPrivatePortfolioDto(); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, portfolio.getUuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(group, null)).isEmpty(); assertThat(db.users().selectGroupPermissions(group, portfolio)).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void fail_if_project_uuid_is_not_found() { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); assertThatThrownBy(() -> newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, "not-found") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_component_is_a_directory() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newDirectory(project, "A/B")); failIfComponentIsNotAProjectOrView(file); } @Test public void fail_when_component_is_a_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "file-uuid")); failIfComponentIsNotAProjectOrView(file); } @Test public void fail_when_component_is_a_subview() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newSubPortfolio(project)); failIfComponentIsNotAProjectOrView(file); } private void failIfComponentIsNotAProjectOrView(ComponentDto file) { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); assertThatThrownBy(() -> newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, file.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void adding_a_project_permission_fails_if_project_is_not_set() { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); assertThatThrownBy(() -> { executeRequest(group, UserRole.ISSUE_ADMIN); }) .isInstanceOf(BadRequestException.class); } @Test public void adding_a_project_permission_fails_if_component_is_not_a_project() { GroupDto group = db.users().insertGroup("sonar-administrators"); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project, null, "file-uuid")); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, file.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_get_request() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setMethod("GET") .setParam(PARAM_GROUP_NAME, "sonar-administrators") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(ServerException.class); } @Test public void fail_when_group_name_is_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'groupName' parameter is missing"); } @Test public void fail_when_permission_is_missing() { GroupDto group = db.users().insertGroup("sonar-administrators"); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_global_administrator() { GroupDto group = db.users().insertGroup(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_project_uuid_and_project_key_are_provided() { GroupDto group = db.users().insertGroup(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute(); }) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } @Test public void adding_global_permission_fails_if_not_administrator() { GroupDto group = db.users().insertGroup("sonar-administrators"); userSession.logIn().addPermission(GlobalPermission.SCAN); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()) .execute(); }) .isInstanceOf(ForbiddenException.class); } @Test public void adding_project_permission_fails_if_not_administrator_of_project() { GroupDto group = db.users().insertGroup("sonar-administrators"); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute(); }) .isInstanceOf(ForbiddenException.class); } /** * User is project administrator but not system administrator */ @Test public void adding_project_permission_is_allowed_to_project_administrators() { GroupDto group = db.users().insertGroup("sonar-administrators"); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectGroupPermissions(group, project)).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void fails_when_adding_any_permission_to_group_AnyOne_on_a_private_project() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); permissionService.getAllProjectPermissions() .forEach(permission -> { try { newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, permission) .execute(); fail("a BadRequestException should have been raised for " + permission); } catch (BadRequestException e) { assertThat(e).hasMessage("No permission can be granted to Anyone on a private component"); } }); } @Test public void no_effect_when_adding_USER_permission_to_group_AnyOne_on_a_public_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void no_effect_when_adding_CODEVIEWER_permission_to_group_AnyOne_on_a_public_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void no_effect_when_adding_USER_permission_to_group_on_a_public_project() { GroupDto group = db.users().insertGroup(); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void no_effect_when_adding_CODEVIEWER_permission_to_group_on_a_public_project() { GroupDto group = db.users().insertGroup(); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void fail_when_using_branch_uuid() { GroupDto group = db.users().insertGroup(); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); assertThatThrownBy(() -> newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute()) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } private void executeRequest(GroupDto groupDto, String permission) { newRequest() .setParam(PARAM_GROUP_NAME, groupDto.getName()) .setParam(PARAM_PERMISSION, permission) .execute(); } }
17,009
36.46696
144
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/AddUserActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN; public class AddUserActionIT extends BasePermissionWsIT<AddUserAction> { private UserDto user; private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); private final Configuration configuration = mock(Configuration.class); @Before public void setUp() { user = db.users().insertUser("ray.bradbury"); } @Override protected AddUserAction buildWsAction() { return new AddUserAction(db.getDbClient(), userSession, newPermissionUpdater(), newPermissionWsSupport(), wsParameters, permissionService, configuration); } @Test public void add_permission_to_user() { loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectPermissionsOfUser(user)).containsOnly(GlobalPermission.ADMINISTER); } @Test public void add_permission_to_project_referenced_by_its_id() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectPermissionsOfUser(user)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void add_permission_to_project_referenced_by_its_key() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectPermissionsOfUser(user)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void add_permission_to_view() { PortfolioDto portfolioDto = db.components().insertPrivatePortfolioDto(); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, portfolioDto.getUuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); assertThat(db.users().selectPermissionsOfUser(user)).isEmpty(); assertThat(db.users().selectEntityPermissionOfUser(user, portfolioDto.getUuid())).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void fail_when_project_uuid_is_unknown() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_component_is_a_directory() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newDirectory(project, "A/B")); failIfComponentIsNotAProjectOrView(file); } @Test public void fail_when_component_is_a_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "file-uuid")); failIfComponentIsNotAProjectOrView(file); } @Test public void fail_when_component_is_a_subview() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newSubPortfolio(project)); failIfComponentIsNotAProjectOrView(file); } private void failIfComponentIsNotAProjectOrView(ComponentDto file) { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, file.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void fail_when_project_permission_without_project() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_when_component_is_not_a_project() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertComponent(newFileDto(project, null, "file-uuid")); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, "file-uuid") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_get_request() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setMethod("GET") .setParam(PARAM_USER_LOGIN, "george.orwell") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(ServerException.class); } @Test public void fail_when_user_login_is_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_permission_is_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, "jrr.tolkien") .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_project_uuid_and_project_key_are_provided() { db.components().insertPrivateProject().getMainBranchComponent(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, "project-uuid") .setParam(PARAM_PROJECT_KEY, "project-key") .execute(); }) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } @Test public void adding_global_permission_fails_if_not_system_administrator() { userSession.logIn(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(ForbiddenException.class); } @Test public void adding_project_permission_fails_if_not_administrator_of_project() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); TestRequest request = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } @Test public void adding_project_permission_fails_if_user_doesnt_exist_and_not_administrator_of_project() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); TestRequest request = newRequest() .setParam(PARAM_USER_LOGIN, "unknown") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } @Test public void adding_project_permission_fails_if_not_administrator_of_project_and_login_param_is_missing() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); TestRequest request = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class); } /** * User is project administrator but not system administrator */ @Test public void adding_project_permission_is_allowed_to_project_administrators() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void no_effect_when_adding_USER_permission_on_a_public_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void no_effect_when_adding_CODEVIEWER_permission_on_a_public_project() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).isEmpty(); } @Test public void fail_when_using_branch_uuid() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); TestRequest request = newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } }
13,640
34.992084
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/BasePermissionWsIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Before; import org.junit.Rule; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.resources.Qualifiers; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.es.EsTester; import org.sonar.server.es.IndexersImpl; import org.sonar.server.permission.GroupPermissionChanger; import org.sonar.server.permission.PermissionUpdater; import org.sonar.server.permission.UserPermissionChanger; import org.sonar.server.permission.index.FooIndexDefinition; import org.sonar.server.permission.index.PermissionIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.usergroups.ws.GroupWsSupport; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.mockito.Mockito.mock; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; public abstract class BasePermissionWsIT<A extends PermissionsWsAction> { @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); @Rule public EsTester es = EsTester.createCustom(new FooIndexDefinition()); protected UserSessionRule userSession = UserSessionRule.standalone(); protected WsActionTester wsTester; protected Configuration configuration = mock(Configuration.class); @Before public void initWsTester() { wsTester = new WsActionTester(buildWsAction()); } protected abstract A buildWsAction(); protected GroupWsSupport newGroupWsSupport() { return new GroupWsSupport(db.getDbClient(), new DefaultGroupFinder(db.getDbClient())); } protected PermissionWsSupport newPermissionWsSupport() { DbClient dbClient = db.getDbClient(); return new PermissionWsSupport(dbClient, configuration, new ComponentFinder(dbClient, newRootResourceTypes()), newGroupWsSupport()); } protected ResourceTypesRule newRootResourceTypes() { return new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); } protected PermissionUpdater newPermissionUpdater() { return new PermissionUpdater( new IndexersImpl(new PermissionIndexer(db.getDbClient(), es.client())), new UserPermissionChanger(db.getDbClient(), new SequenceUuidFactory()), new GroupPermissionChanger(db.getDbClient(), new SequenceUuidFactory())); } protected TestRequest newRequest() { return wsTester.newRequest().setMethod("POST"); } protected void loginAsAdmin() { userSession.logIn().addPermission(ADMINISTER); } protected PermissionTemplateDto selectPermissionTemplate(String name) { return db.getDbClient().permissionTemplateDao().selectByName(db.getSession(), name); } protected PermissionTemplateDto addTemplate() { PermissionTemplateDto dto = newPermissionTemplateDto(); db.getDbClient().permissionTemplateDao().insert(db.getSession(), dto); db.commit(); return dto; } }
4,182
37.376147
136
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/GroupsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.security.DefaultGroups; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; public class GroupsActionIT extends BasePermissionWsIT<GroupsAction> { private GroupDto group1; private GroupDto group2; private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class); @Override protected GroupsAction buildWsAction() { return new GroupsAction( db.getDbClient(), userSession, newPermissionWsSupport(), wsParameters, managedInstanceService); } @Before public void setUp() { group1 = db.users().insertGroup("group-1-name"); group2 = db.users().insertGroup("group-2-name"); GroupDto group3 = db.users().insertGroup("group-3-name"); db.users().insertPermissionOnGroup(group1, GlobalPermission.SCAN); db.users().insertPermissionOnGroup(group2, GlobalPermission.SCAN); db.users().insertPermissionOnGroup(group3, GlobalPermission.ADMINISTER); db.users().insertPermissionOnAnyone(GlobalPermission.SCAN); db.commit(); } @Test public void verify_definition() { Action wsDef = wsTester.getDef(); assertThat(wsDef.isInternal()).isTrue(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isFalse(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsExactlyInAnyOrder( tuple("10.0", "Response includes 'managed' field."), tuple("8.4", "Field 'id' in the response is deprecated. Format changes from integer to string."), tuple("7.4", "The response list is returning all groups even those without permissions, the groups with permission are at the top of the list.")); } @Test public void search_for_groups_with_one_permission() { loginAsAdmin(); String json = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .execute() .getInput(); assertJson(json).isSimilarTo("{\n" + " \"paging\": {\n" + " \"pageIndex\": 1,\n" + " \"pageSize\": 20,\n" + " \"total\": 3\n" + " },\n" + " \"groups\": [\n" + " {\n" + " \"name\": \"Anyone\",\n" + " \"permissions\": [\n" + " \"scan\"\n" + " ]\n" + " },\n" + " {\n" + " \"name\": \"group-1-name\",\n" + " \"description\": \"" + group1.getDescription() + "\",\n" + " \"permissions\": [\n" + " \"scan\"\n" + " ],\n" + " \"managed\": false\n" + " },\n" + " {\n" + " \"name\": \"group-2-name\",\n" + " \"description\": \"" + group2.getDescription() + "\",\n" + " \"permissions\": [\n" + " \"scan\"\n" + " ],\n" + " \"managed\": false\n" + " }\n" + " ]\n" + "}\n"); } @Test public void search_with_selection() { loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .execute() .getInput(); assertThat(result).containsSubsequence(DefaultGroups.ANYONE, "group-1", "group-2"); } @Test public void search_groups_with_pagination() { loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .setParam(PAGE_SIZE, "1") .setParam(PAGE, "3") .execute() .getInput(); assertThat(result).contains("group-2") .doesNotContain("group-1") .doesNotContain("group-3"); } @Test public void search_groups_with_query() { loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .setParam(TEXT_QUERY, "group-") .execute() .getInput(); assertThat(result) .contains("group-1", "group-2") .doesNotContain(DefaultGroups.ANYONE); } @Test public void search_groups_with_project_permissions() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); GroupDto group = db.users().insertGroup("project-group-name"); db.users().insertEntityPermissionOnGroup(group, ISSUE_ADMIN, project); ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto(); GroupDto anotherGroup = db.users().insertGroup("another-project-group-name"); db.users().insertEntityPermissionOnGroup(anotherGroup, ISSUE_ADMIN, anotherProject); GroupDto groupWithoutPermission = db.users().insertGroup("group-without-permission"); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); String result = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, project.getUuid()) .execute() .getInput(); assertThat(result).contains(group.getName()) .doesNotContain(anotherGroup.getName()) .doesNotContain(groupWithoutPermission.getName()); } @Test public void return_also_groups_without_permission_when_search_query() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); GroupDto group = db.users().insertGroup("group-with-permission"); db.users().insertEntityPermissionOnGroup(group, ISSUE_ADMIN, project); GroupDto groupWithoutPermission = db.users().insertGroup("group-without-permission"); GroupDto anotherGroup = db.users().insertGroup("another-group"); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(TEXT_QUERY, "group-with") .execute() .getInput(); assertThat(result).contains(group.getName()) .doesNotContain(groupWithoutPermission.getName()) .doesNotContain(anotherGroup.getName()); } @Test public void return_only_groups_with_permission_when_no_search_query() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); GroupDto group = db.users().insertGroup("project-group-name"); db.users().insertEntityPermissionOnGroup(group, ISSUE_ADMIN, project); GroupDto groupWithoutPermission = db.users().insertGroup("group-without-permission"); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, project.getUuid()) .execute() .getInput(); assertThat(result).contains(group.getName()).doesNotContain(groupWithoutPermission.getName()); } @Test public void return_anyone_group_when_search_query_and_no_param_permission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); GroupDto group = db.users().insertGroup("group-with-permission"); db.users().insertEntityPermissionOnGroup(group, ISSUE_ADMIN, project); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(TEXT_QUERY, "nyo") .execute() .getInput(); assertThat(result).contains("Anyone"); } @Test public void search_groups_on_views() { PortfolioDto portfolio = db.components().insertPrivatePortfolioDto("view-uuid"); GroupDto group = db.users().insertGroup("project-group-name"); db.users().insertEntityPermissionOnGroup(group, ISSUE_ADMIN, portfolio); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, "view-uuid") .execute() .getInput(); assertThat(result).contains("project-group-name") .doesNotContain("group-1") .doesNotContain("group-2") .doesNotContain("group-3"); } @Test public void return_isManaged() { PortfolioDto portfolio = db.components().insertPrivatePortfolioDto("view-uuid"); GroupDto managedGroup = db.users().insertGroup("managed-group"); GroupDto localGroup = db.users().insertGroup("local-group"); db.users().insertEntityPermissionOnGroup(managedGroup, ISSUE_ADMIN, portfolio); db.users().insertEntityPermissionOnGroup(localGroup, ISSUE_ADMIN, portfolio); mockGroupsAsManaged(managedGroup.getUuid()); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, "view-uuid") .execute() .getInput(); assertJson(result).isSimilarTo( "{\n" + " \"paging\": {\n" + " \"pageIndex\": 1,\n" + " \"pageSize\": 20,\n" + " \"total\": 2\n" + " },\n" + " \"groups\": [\n" + " {\n" + " \"name\": \"local-group\",\n" + " \"managed\": false\n" + " },\n" + " {\n" + " \"name\": \"managed-group\",\n" + " \"managed\": true\n" + " }\n" + " ]\n" + "}" ); } @Test public void fail_if_not_logged_in() { assertThatThrownBy(() -> { userSession.anonymous(); newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { assertThatThrownBy(() -> { userSession.logIn("login"); newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .execute(); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_project_uuid_and_project_key_are_provided() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); assertThatThrownBy(() -> { loginAsAdmin(); newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.SCAN.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_when_using_branch_uuid() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project); GroupDto group = db.users().insertGroup(); db.users().insertProjectPermissionOnGroup(group, ISSUE_ADMIN, project); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, branch.uuid()) .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } private void mockGroupsAsManaged(String... groupUuids) { when(managedInstanceService.getGroupUuidToManaged(any(), any())).thenAnswer(invocation -> { Set<?> allGroupUuids = invocation.getArgument(1, Set.class); return allGroupUuids.stream() .map(groupUuid -> (String) groupUuid) .collect(toMap(identity(), userUuid -> Set.of(groupUuids).contains(userUuid))); } ); } }
14,009
35.108247
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/RemoveGroupActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.GroupPermissionDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; @RunWith(DataProviderRunner.class) public class RemoveGroupActionIT extends BasePermissionWsIT<RemoveGroupAction> { private GroupDto aGroup; private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); @Before public void setUp() { aGroup = db.users().insertGroup("sonar-administrators"); } @Override protected RemoveGroupAction buildWsAction() { return new RemoveGroupAction(db.getDbClient(), userSession, newPermissionUpdater(), newPermissionWsSupport(), wsParameters, permissionService); } @Test public void wsAction_shouldHaveDefinition() { Action wsDef = wsTester.getDef(); assertThat(wsDef.isInternal()).isFalse(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isTrue(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly( tuple("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."), tuple("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead.")); } @Test public void wsAction_shouldRemoveGlobalPermission() { db.users().insertPermissionOnGroup(aGroup, GlobalPermission.ADMINISTER); db.users().insertPermissionOnGroup(aGroup, GlobalPermission.PROVISION_PROJECTS); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()) .execute(); assertThat(db.users().selectGroupPermissions(aGroup, null)).containsOnly(GlobalPermission.ADMINISTER.getKey()); } @Test public void wsAction_shouldRemoveProjectPermission() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.users().insertPermissionOnGroup(aGroup, GlobalPermission.ADMINISTER); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ADMIN, project); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ISSUE_ADMIN, project); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.ADMIN) .execute(); assertThat(db.users().selectGroupPermissions(aGroup, null)).containsOnly(GlobalPermission.ADMINISTER.getKey()); assertThat(db.users().selectGroupPermissions(aGroup, project)).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void wsAction_whenUsingViewUuid_shouldRemovePermission() { EntityDto portfolio = db.components().insertPrivatePortfolioDto(); db.users().insertPermissionOnGroup(aGroup, GlobalPermission.ADMINISTER); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ADMIN, portfolio); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ISSUE_ADMIN, portfolio); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_ID, portfolio.getUuid()) .setParam(PARAM_PERMISSION, UserRole.ADMIN) .execute(); assertThat(db.users().selectGroupPermissions(aGroup, null)).containsOnly(GlobalPermission.ADMINISTER.getKey()); assertThat(db.users().selectGroupPermissions(aGroup, portfolio)).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void wsAction_whenUsingProjectKey_shouldRemovePermission() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.users().insertPermissionOnGroup(aGroup, GlobalPermission.ADMINISTER); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ADMIN, project); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ISSUE_ADMIN, project); loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PERMISSION, UserRole.ADMIN) .execute(); assertThat(db.users().selectGroupPermissions(aGroup, null)).containsOnly(GlobalPermission.ADMINISTER.getKey()); assertThat(db.users().selectGroupPermissions(aGroup, project)).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void wsAction_whenLastAdminPermission_shouldFail() { db.users().insertPermissionOnGroup(aGroup, GlobalPermission.ADMINISTER); db.users().insertPermissionOnGroup(aGroup, GlobalPermission.PROVISION_PROJECTS); loginAsAdmin(); String administerPermission = GlobalPermission.ADMINISTER.getKey(); assertThatThrownBy(() -> executeRequest(aGroup, administerPermission)) .isInstanceOf(BadRequestException.class) .hasMessage("Last group with permission 'admin'. Permission cannot be removed."); } @Test public void wsAction_whenProjectNotFound_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void wsAction_whenUsingProjectPermissionWithoutProject_shouldFail() { loginAsAdmin(); assertThatThrownBy(() -> executeRequest(aGroup, UserRole.ISSUE_ADMIN)) .isInstanceOf(BadRequestException.class) .hasMessage("Invalid global permission 'issueadmin'. Valid values are [admin, gateadmin, profileadmin, provisioning, scan]"); } @Test public void wsAction_whenComponentIsDirectory_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newDirectory(project, "A/B")); failIfComponentIsNotAProjectOrView(file); } @Test public void wsAction_whenComponentIsFile_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "file-uuid")); failIfComponentIsNotAProjectOrView(file); } @Test public void wsAction_whenComponentIsSubview_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newSubPortfolio(project)); failIfComponentIsNotAProjectOrView(file); } private void failIfComponentIsNotAProjectOrView(ComponentDto file) { loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_ID, file.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void wsAction_whenGroupNameIsMissing_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest().setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'groupName' parameter is missing"); } @Test public void wsAction_whenPermissionNameAndIdMissing_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest().setParam(PARAM_GROUP_NAME, aGroup.getName()); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'permission' parameter is missing"); } @Test public void wsAction_whenProjectUuidAndProjectKeyAreProvided_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } private void executeRequest(GroupDto groupDto, String permission) { newRequest() .setParam(PARAM_GROUP_NAME, groupDto.getName()) .setParam(PARAM_PERMISSION, permission) .execute(); } @Test public void wsAction_whenRemovingGlobalPermissionAndNotSystemAdmin_shouldFail() { userSession.logIn(); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(ForbiddenException.class); } @Test public void wsAction_whenRemovingProjectPermissionAndNotProjectAdmin_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(ForbiddenException.class); } @Test public void wsAction_whenRemovingProjectPermissionAsProjectAdminButNotSystemAdmin_shouldRemovePermission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.CODEVIEWER, project); db.users().insertEntityPermissionOnGroup(aGroup, UserRole.ISSUE_ADMIN, project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_GROUP_NAME, aGroup.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectGroupPermissions(aGroup, project)).containsOnly(UserRole.CODEVIEWER); } @Test public void wsAction_whenRemovingAnyPermissionFromGroupAnyoneOnPrivateProject_shouldHaveNoEffect() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); permissionService.getAllProjectPermissions() .forEach(perm -> unsafeInsertProjectPermissionOnAnyone(perm, project)); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); permissionService.getAllProjectPermissions() .forEach(permission -> { newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, permission) .execute(); assertThat(db.users().selectAnyonePermissions(project.getUuid())).contains(permission); }); } @Test public void wsAction_whenRemovingBrowsePermissionFromGroupAnyoneOnPublicProject_shouldFail() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void wsAction_whenRemovingCodeviewerPermissionFromGroupAnyoneOnPublicProject_shouldFail() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, "anyone") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void wsAction_whenRemovingBrowsePermissionFromGroupOnPublicProject_shouldFail() { GroupDto group = db.users().insertGroup(); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void wsAction_whenRemovingCodeviewerPermissionFromGroupOnPublicProject() { GroupDto group = db.users().insertGroup(); ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void wsAction_whenUsingBranchUuid_shouldFail() { GroupDto group = db.users().insertGroup(); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); TestRequest testRequest = newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void wsAction_whenRemovingLastOwnBrowsePermissionForPrivateProject_shouldFail() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(); GroupDto projectAdminGroup = db.users().insertGroup(); db.users().insertEntityPermissionOnGroup(projectAdminGroup, UserRole.USER, project); db.users().insertEntityPermissionOnGroup(projectAdminGroup, UserRole.ADMIN, project); userSession.logIn(user).setGroups(projectAdminGroup).addProjectPermission(UserRole.USER, project).addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_GROUP_NAME, projectAdminGroup.getName()) .setParam(PARAM_PERMISSION, UserRole.USER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission 'Browse' cannot be removed from a private project for a project administrator."); } @Test public void wsAction_whenRemovingOwnBrowsePermissionAndHavePermissionFromOtherGroup_shouldRemovePermission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(); GroupDto projectAdminGroup = db.users().insertGroup(); GroupDto otherProjectAdminGroup = db.users().insertGroup(); db.users().insertEntityPermissionOnGroup(projectAdminGroup, UserRole.USER, project); db.users().insertEntityPermissionOnGroup(projectAdminGroup, UserRole.ADMIN, project); db.users().insertEntityPermissionOnGroup(otherProjectAdminGroup, UserRole.USER, project); db.users().insertEntityPermissionOnGroup(otherProjectAdminGroup, UserRole.ADMIN, project); userSession.logIn(user).setGroups(projectAdminGroup, otherProjectAdminGroup).addProjectPermission(UserRole.USER, project).addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_GROUP_NAME, projectAdminGroup.getName()) .setParam(PARAM_PERMISSION, UserRole.USER) .execute(); assertThat(db.users().selectGroupPermissions(projectAdminGroup, project)).containsOnly(UserRole.ADMIN); assertThat(db.users().selectGroupPermissions(otherProjectAdminGroup, project)).containsExactlyInAnyOrder(UserRole.USER, UserRole.ADMIN); } private void unsafeInsertProjectPermissionOnAnyone(String perm, ProjectDto project) { GroupPermissionDto dto = new GroupPermissionDto() .setUuid(Uuids.createFast()) .setGroupUuid(null) .setRole(perm) .setEntityUuid(project.getUuid()) .setEntityName(project.getName()); db.getDbClient().groupPermissionDao().insert(db.getSession(), dto, project, null); db.commit(); } }
19,838
41.756466
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/RemoveUserActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.ServerException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.ws.TestRequest; import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.ComponentTesting.newSubPortfolio; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN; public class RemoveUserActionIT extends BasePermissionWsIT<RemoveUserAction> { private static final String A_LOGIN = "ray.bradbury"; private UserDto user; private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); @Before public void setUp() { user = db.users().insertUser(A_LOGIN); } @Override protected RemoveUserAction buildWsAction() { return new RemoveUserAction(db.getDbClient(), userSession, newPermissionUpdater(), newPermissionWsSupport(), wsParameters, permissionService); } @Test public void wsAction_shouldRemovePermissionFromUser() { db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS); db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER_QUALITY_GATES); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER_QUALITY_GATES.getKey()) .execute(); assertThat(db.users().selectPermissionsOfUser(user)).containsOnly(GlobalPermission.PROVISION_PROJECTS); } @Test public void wsAction_whenAdminRemoveOwnGlobalAdminRight_shouldFail() { db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER); loginAsAdmin(); UserDto admin = db.users().insertUser(userSession.getLogin()); db.users().insertGlobalPermissionOnUser(admin, GlobalPermission.ADMINISTER); TestRequest request = newRequest() .setParam(PARAM_USER_LOGIN, userSession.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("As an admin, you can't remove your own admin right"); } @Test public void wsAction_whenProjectAdminRemoveOwnProjectAdminRight_shouldFail() { loginAsAdmin(); UserDto admin = db.users().insertUser(userSession.getLogin()); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.users().insertProjectPermissionOnUser(admin, GlobalPermission.ADMINISTER.getKey(), project); TestRequest request = newRequest() .setParam(PARAM_USER_LOGIN, userSession.getLogin()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("As an admin, you can't remove your own admin right"); } @Test public void wsAction_whenPrivateProjectAdminRemovesOwnBrowsePermission_shouldFail() { loginAsAdmin(); UserDto admin = db.users().insertUser(requireNonNull(userSession.getLogin())); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(admin, GlobalPermission.ADMINISTER.getKey(), project); TestRequest request = newRequest() .setParam(PARAM_USER_LOGIN, userSession.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission 'Browse' cannot be removed from a private project for a project administrator."); } @Test public void wsAction_whenRemoveAdminPermissionAndLastAdmin_shouldFail() { db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER); loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, UserRole.ADMIN); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Last user with permission 'admin'. Permission cannot be removed."); } @Test public void wsAction_whenProject_shouldRemovePermission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, project); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER) .execute(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(UserRole.ISSUE_ADMIN); } @Test public void wsAction_whenUsingProjectKey_shouldRemovePermission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); db.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, project); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(UserRole.CODEVIEWER); } @Test public void wsAction_whenUsingViewUuid_shouldRemovePermission() { ComponentDto view = db.components().insertPrivatePortfolio(); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, view); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, view); loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_KEY, view.getKey()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectEntityPermissionOfUser(user, view.uuid())).containsOnly(UserRole.ADMIN); } @Test public void wsAction_whenProjectNotFound_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, "unknown-project-uuid") .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class); } @Test public void wsAction_whenRemovingProjectPermissionWithoutProject_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class); } @Test public void wsAction_whenComponentIsDirectory_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newDirectory(project, "A/B")); failIfComponentIsNotAProjectOrView(file); } @Test public void wsAction_whenComponentIsFile_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(project, null, "file-uuid")); failIfComponentIsNotAProjectOrView(file); } @Test public void wsAction_whenComponentIsSubview_shouldFail() { ComponentDto portfolio = db.components().insertPrivatePortfolio(); ComponentDto file = db.components().insertComponent(newSubPortfolio(portfolio)); failIfComponentIsNotAProjectOrView(file); } private void failIfComponentIsNotAProjectOrView(ComponentDto file) { loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, file.uuid()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void wsAction_whenGetRequest_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest() .setMethod("GET") .setParam(PARAM_USER_LOGIN, "george.orwell") .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(ServerException.class); } @Test public void wsAction_whenUserLoginIsMissing_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest().setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class); } @Test public void wsAction_whenPermissionIsMissing_shouldFail() { loginAsAdmin(); TestRequest testRequest = newRequest().setParam(PARAM_USER_LOGIN, user.getLogin()); assertThatThrownBy(testRequest::execute) .isInstanceOf(IllegalArgumentException.class); } @Test public void wsAction_whenProjectUuidAndProjectKeyProvided_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); loginAsAdmin(); TestRequest testRequest = newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } @Test public void wsAction_whenGlobalPermissionAndNotSystemAdmin_shouldFail() { userSession.logIn(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.PROVISION_PROJECTS.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(ForbiddenException.class); } @Test public void wsAction_whenProjectPermissionAndNotProjectAdmin_shouldFail() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .setParam(PARAM_PROJECT_KEY, project.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(ForbiddenException.class); } /** * User is project administrator but not system administrator */ @Test public void wsAction_whenProjectPermissionAndProjectAdmin_shouldRemovePermission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, project); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .execute(); assertThat(db.users().selectEntityPermissionOfUser(user, project.getUuid())).containsOnly(UserRole.CODEVIEWER); } @Test public void wsAction_whenBrowsePermissionAndPublicProject_shouldFail() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.USER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission user can't be removed from a public component"); } @Test public void wsAction_whenCodeviewerPermissionAndPublicProject_shouldFail() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); TestRequest testRequest = newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_PERMISSION, UserRole.CODEVIEWER); assertThatThrownBy(testRequest::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Permission codeviewer can't be removed from a public component"); } @Test public void wsAction_whenUsingBranchUuid_shouldFail() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ComponentDto branch = db.components().insertProjectBranch(project); TestRequest testRequest = newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()); assertThatThrownBy(testRequest::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } }
15,600
38.0025
146
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/UsersActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws; import java.util.Set; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.server.ws.WebService.SelectionMode; import org.sonar.api.web.UserRole; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.issue.AvatarResolverImpl; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static org.apache.commons.lang.StringUtils.countMatches; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN; public class UsersActionIT extends BasePermissionWsIT<UsersAction> { private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); private final RequestValidator requestValidator = new RequestValidator(permissionService); private final ManagedInstanceService managedInstanceService = mock(ManagedInstanceService.class); @Override protected UsersAction buildWsAction() { return new UsersAction(db.getDbClient(), userSession, newPermissionWsSupport(), new AvatarResolverImpl(), wsParameters, requestValidator, managedInstanceService); } @Test public void search_for_users_with_response_example() { UserDto user1 = db.users().insertUser(newUserDto().setLogin("admin").setName("Administrator").setEmail("admin@admin.com")); UserDto user2 = db.users().insertUser(newUserDto().setLogin("adam.west").setName("Adam West").setEmail("adamwest@adamwest.com")); UserDto user3 = db.users().insertUser(newUserDto().setLogin("george.orwell").setName("George Orwell").setEmail("george.orwell@1984.net")); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER_QUALITY_PROFILES); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.ADMINISTER_QUALITY_GATES); db.users().insertGlobalPermissionOnUser(user3, GlobalPermission.SCAN); mockUsersAsManaged(user3.getUuid()); loginAsAdmin(); String result = newRequest().execute().getInput(); assertJson(result).withStrictArrayOrder().isSimilarTo(getClass().getResource("users-example.json")); } @Test public void search_for_users_with_one_permission() { insertUsersHavingGlobalPermissions(); loginAsAdmin(); String result = newRequest().setParam("permission", "scan").execute().getInput(); assertJson(result).withStrictArrayOrder().isSimilarTo(getClass().getResource("UsersActionIT/users.json")); } @Test public void search_for_users_with_permission_on_project() { // User has permission on project ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(newUserDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); // User has permission on another project ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto(); UserDto userHavePermissionOnAnotherProject = db.users().insertUser(newUserDto()); db.users().insertProjectPermissionOnUser(userHavePermissionOnAnotherProject, UserRole.ISSUE_ADMIN, anotherProject); // User has no permission UserDto withoutPermission = db.users().insertUser(newUserDto()); userSession.logIn().addProjectPermission(GlobalPermission.ADMINISTER.getKey(), project); String result = newRequest() .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .setParam(PARAM_PROJECT_ID, project.getUuid()) .execute() .getInput(); assertThat(result).contains(user.getLogin()) .doesNotContain(userHavePermissionOnAnotherProject.getLogin()) .doesNotContain(withoutPermission.getLogin()); } @Test public void search_also_for_users_without_permission_when_filtering_name() { // User with permission on project ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(newUserDto("with-permission-login", "with-permission-name", "with-permission-email")); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); // User without permission UserDto withoutPermission = db.users().insertUser(newUserDto("without-permission-login", "without-permission-name", "without-permission-email")); UserDto anotherUser = db.users().insertUser(newUserDto("another-user", "another-user", "another-user")); loginAsAdmin(); String result = newRequest() .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(TEXT_QUERY, "with") .execute() .getInput(); assertThat(result).contains(user.getLogin(), withoutPermission.getLogin()).doesNotContain(anotherUser.getLogin()); } @Test public void search_also_for_users_without_permission_when_filtering_email() { // User with permission on project ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(newUserDto("with-permission-login", "with-permission-name", "with-permission-email")); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); // User without permission UserDto withoutPermission = db.users().insertUser(newUserDto("without-permission-login", "without-permission-name", "without-permission-email")); UserDto anotherUser = db.users().insertUser(newUserDto("another-user", "another-user", "another-user")); loginAsAdmin(); String result = newRequest().setParam(PARAM_PROJECT_ID, project.getUuid()).setParam(TEXT_QUERY, "email").execute().getInput(); assertThat(result).contains(user.getLogin(), withoutPermission.getLogin()).doesNotContain(anotherUser.getLogin()); } @Test public void search_also_for_users_without_permission_when_filtering_login() { // User with permission on project ProjectDto project = db.components().insertPrivateProject().getProjectDto(); UserDto user = db.users().insertUser(newUserDto("with-permission-login", "with-permission-name", "with-permission-email")); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); // User without permission UserDto withoutPermission = db.users().insertUser(newUserDto("without-permission-login", "without-permission-name", "without-permission-email")); UserDto anotherUser = db.users().insertUser(newUserDto("another-user", "another-user", "another-user")); loginAsAdmin(); String result = newRequest().setParam(PARAM_PROJECT_ID, project.getUuid()).setParam(TEXT_QUERY, "login").execute().getInput(); assertThat(result).contains(user.getLogin(), withoutPermission.getLogin()).doesNotContain(anotherUser.getLogin()); } @Test public void search_for_users_with_query_as_a_parameter() { insertUsersHavingGlobalPermissions(); loginAsAdmin(); String result = newRequest() .setParam("permission", "scan") .setParam(TEXT_QUERY, "ame-1") .execute() .getInput(); assertThat(result).contains("login-1") .doesNotContain("login-2") .doesNotContain("login-3"); } @Test public void search_for_users_with_select_as_a_parameter() { insertUsersHavingGlobalPermissions(); loginAsAdmin(); String result = newRequest() .execute() .getInput(); assertThat(result).contains("login-1", "login-2", "login-3"); } @Test public void search_for_users_is_paginated() { for (int i = 9; i >= 0; i--) { UserDto user = db.users().insertUser(newUserDto().setName("user-" + i)); db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER); db.users().insertGlobalPermissionOnUser(user, GlobalPermission.ADMINISTER_QUALITY_GATES); } loginAsAdmin(); assertJson(newRequest().setParam(PAGE, "1").setParam(PAGE_SIZE, "2").execute().getInput()).withStrictArrayOrder().isSimilarTo("{\n" + " \"paging\": {\n" + " \"pageIndex\": 1,\n" + " \"pageSize\": 2,\n" + " \"total\": 10\n" + " },\n" + " \"users\": [\n" + " {\n" + " \"name\": \"user-0\"\n" + " },\n" + " {\n" + " \"name\": \"user-1\"\n" + " }\n" + " ]\n" + "}"); assertJson(newRequest().setParam(PAGE, "3").setParam(PAGE_SIZE, "4").execute().getInput()).withStrictArrayOrder().isSimilarTo("{\n" + " \"paging\": {\n" + " \"pageIndex\": 3,\n" + " \"pageSize\": 4,\n" + " \"total\": 10\n" + " },\n" + " \"users\": [\n" + " {\n" + " \"name\": \"user-8\"\n" + " },\n" + " {\n" + " \"name\": \"user-9\"\n" + " }\n" + " ]\n" + "}"); } @Test public void return_more_than_20_permissions() { loginAsAdmin(); for (int i = 0; i < 30; i++) { UserDto user = db.users().insertUser(newUserDto().setLogin("user-" + i)); db.users().insertGlobalPermissionOnUser(user, GlobalPermission.SCAN); db.users().insertGlobalPermissionOnUser(user, GlobalPermission.PROVISION_PROJECTS); } String result = newRequest() .setParam(PAGE_SIZE, "100") .execute() .getInput(); assertThat(countMatches(result, "scan")).isEqualTo(30); } @Test public void fail_if_project_permission_without_project() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ISSUE_ADMIN) .setParam(Param.SELECTED, SelectionMode.ALL.value()) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn("login"); assertThatThrownBy(() -> { newRequest() .setParam("permission", GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { userSession.anonymous(); assertThatThrownBy(() -> { newRequest() .setParam("permission", GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_project_uuid_and_project_key_are_provided() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); loginAsAdmin(); assertThatThrownBy(() -> newRequest() .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute()) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } @Test public void fail_if_search_query_is_too_short() { loginAsAdmin(); assertThatThrownBy(() -> newRequest().setParam(TEXT_QUERY, "ab").execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'q' length (2) is shorter than the minimum authorized (3)"); } @Test public void fail_when_using_branch_uuid() { UserDto user = db.users().insertUser(newUserDto()); ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, project); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, GlobalPermission.ADMINISTER.getKey()) .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } private void insertUsersHavingGlobalPermissions() { UserDto user1 = db.users().insertUser(newUserDto("login-1", "name-1", "email-1")); UserDto user2 = db.users().insertUser(newUserDto("login-2", "name-2", "email-2")); UserDto user3 = db.users().insertUser(newUserDto("login-3", "name-3", "email-3")); db.users().insertGlobalPermissionOnUser(user1, GlobalPermission.SCAN); db.users().insertGlobalPermissionOnUser(user2, GlobalPermission.SCAN); db.users().insertGlobalPermissionOnUser(user3, GlobalPermission.ADMINISTER); mockUsersAsManaged(user1.getUuid()); } private void mockUsersAsManaged(String... userUuids) { when(managedInstanceService.getUserUuidToManaged(any(), any())).thenAnswer(invocation -> { Set<?> allUsersUuids = invocation.getArgument(1, Set.class); return allUsersUuids.stream() .map(userUuid -> (String) userUuid) .collect(toMap(identity(), userUuid -> Set.of(userUuids).contains(userUuid))); } ); } }
15,411
40.654054
166
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.web.UserRole; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.security.DefaultGroups.ANYONE; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class AddGroupToTemplateActionIT extends BasePermissionWsIT<AddGroupToTemplateAction> { private PermissionTemplateDto template; private GroupDto group; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); @Override protected AddGroupToTemplateAction buildWsAction() { return new AddGroupToTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, wsParameters); } @Before public void setUp() { template = db.permissionTemplates().insertTemplate(); group = db.users().insertGroup("group-name"); } @Test public void verify_definition() { Action wsDef = wsTester.getDef(); assertThat(wsDef.isInternal()).isFalse(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isTrue(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly( tuple("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead."), tuple("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead.")); } @Test public void add_group_to_template() { loginAsAdmin(); newRequest(group.getName(), template.getUuid(), CODEVIEWER); assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(group.getName()); } @Test public void add_group_to_template_by_name() { loginAsAdmin(); newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, CODEVIEWER) .setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase()) .execute(); assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(group.getName()); } @Test public void does_not_add_a_group_twice() { loginAsAdmin(); newRequest(group.getName(), template.getUuid(), ISSUE_ADMIN); newRequest(group.getName(), template.getUuid(), ISSUE_ADMIN); assertThat(getGroupNamesInTemplateAndPermission(template, ISSUE_ADMIN)).containsExactly(group.getName()); } @Test public void add_anyone_group_to_template() { loginAsAdmin(); newRequest(ANYONE, template.getUuid(), CODEVIEWER); assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(ANYONE); } @Test public void fail_if_add_anyone_group_to_admin_permission() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(ANYONE, template.getUuid(), ADMIN)) .isInstanceOf(BadRequestException.class) .hasMessage(String.format("It is not possible to add the '%s' permission to the group 'Anyone'.", UserRole.ADMIN)); } @Test public void fail_if_not_a_project_permission() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), PROVISION_PROJECTS.getKey())) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn(); assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), CODEVIEWER)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_group_params_missing() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(null, template.getUuid(), CODEVIEWER)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_uuid_and_name_missing() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(group.getName(), null, CODEVIEWER)) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_group_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> newRequest("unknown-group-name", template.getUuid(), CODEVIEWER)) .isInstanceOf(NotFoundException.class) .hasMessage("No group with name 'unknown-group-name'"); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(group.getName(), "unknown-key", CODEVIEWER)) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String groupName, @Nullable String templateKey, @Nullable String permission) { TestRequest request = newRequest(); if (groupName != null) { request.setParam(PARAM_GROUP_NAME, groupName); } if (templateKey != null) { request.setParam(PARAM_TEMPLATE_ID, templateKey); } if (permission != null) { request.setParam(PARAM_PERMISSION, permission); } request.execute(); } private List<String> getGroupNamesInTemplateAndPermission(PermissionTemplateDto template, String permission) { PermissionQuery query = PermissionQuery.builder().setPermission(permission).build(); return db.getDbClient().permissionTemplateDao() .selectGroupNamesByQueryAndTemplate(db.getSession(), query, template.getUuid()); } }
7,990
35.824885
121
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/AddProjectCreatorToTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class AddProjectCreatorToTemplateActionIT extends BasePermissionWsIT<AddProjectCreatorToTemplateAction> { private System2 system = spy(System2.INSTANCE); private PermissionTemplateDto template; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); private RequestValidator requestValidator = new RequestValidator(permissionService); @Override protected AddProjectCreatorToTemplateAction buildWsAction() { return new AddProjectCreatorToTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, system, wsParameters, requestValidator); } @Before public void setUp() { template = db.permissionTemplates().insertTemplate(); when(system.now()).thenReturn(2_000_000_000L); } @Test public void insert_row_when_no_template_permission() { loginAsAdmin(); newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); assertThatProjectCreatorIsPresentFor(UserRole.ADMIN, template.getUuid()); } @Test public void update_row_when_existing_template_permission() { loginAsAdmin(); PermissionTemplateCharacteristicDto characteristic = db.getDbClient().permissionTemplateCharacteristicDao().insert(db.getSession(), new PermissionTemplateCharacteristicDto() .setUuid(Uuids.createFast()) .setTemplateUuid(template.getUuid()) .setPermission(UserRole.USER) .setWithProjectCreator(false) .setCreatedAt(1_000_000_000L) .setUpdatedAt(1_000_000_000L), template.getName()); db.commit(); when(system.now()).thenReturn(3_000_000_000L); newRequest() .setParam(PARAM_PERMISSION, UserRole.USER) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .execute(); assertThatProjectCreatorIsPresentFor(UserRole.USER, template.getUuid()); PermissionTemplateCharacteristicDto reloaded = reload(characteristic); assertThat(reloaded.getCreatedAt()).isEqualTo(1_000_000_000L); assertThat(reloaded.getUpdatedAt()).isEqualTo(3_000_000_000L); } @Test public void fail_when_template_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, "42") .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_permission_is_not_a_project_permission() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, ADMINISTER_QUALITY_GATES.getKey()) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); }) .isInstanceOf(ForbiddenException.class); } private void assertThatProjectCreatorIsPresentFor(String permission, String templateUuid) { Optional<PermissionTemplateCharacteristicDto> templatePermission = db.getDbClient().permissionTemplateCharacteristicDao().selectByPermissionAndTemplateId(db.getSession(), permission, templateUuid); assertThat(templatePermission).isPresent(); assertThat(templatePermission.get().getWithProjectCreator()).isTrue(); } private PermissionTemplateCharacteristicDto reload(PermissionTemplateCharacteristicDto characteristic) { return db.getDbClient().permissionTemplateCharacteristicDao().selectByPermissionAndTemplateId(db.getSession(), characteristic.getPermission(), characteristic.getTemplateUuid()) .get(); } }
6,338
38.61875
180
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/AddUserToTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN; public class AddUserToTemplateActionIT extends BasePermissionWsIT<AddUserToTemplateAction> { private UserDto user; private PermissionTemplateDto permissionTemplate; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); @Override protected AddUserToTemplateAction buildWsAction() { return new AddUserToTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, wsParameters); } @Before public void setUp() { user = db.users().insertUser("user-login"); permissionTemplate = db.permissionTemplates().insertTemplate(); } @Test public void add_user_to_template() { loginAsAdmin(); newRequest(user.getLogin(), permissionTemplate.getUuid(), CODEVIEWER); assertThat(getLoginsInTemplateAndPermission(permissionTemplate, CODEVIEWER)).containsExactly(user.getLogin()); } @Test public void add_user_to_template_by_name() { loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, CODEVIEWER) .setParam(PARAM_TEMPLATE_NAME, permissionTemplate.getName().toUpperCase()) .execute(); assertThat(getLoginsInTemplateAndPermission(permissionTemplate, CODEVIEWER)).containsExactly(user.getLogin()); } @Test public void does_not_add_a_user_twice() { loginAsAdmin(); newRequest(user.getLogin(), permissionTemplate.getUuid(), ISSUE_ADMIN); newRequest(user.getLogin(), permissionTemplate.getUuid(), ISSUE_ADMIN); assertThat(getLoginsInTemplateAndPermission(permissionTemplate, ISSUE_ADMIN)).containsExactly(user.getLogin()); } @Test public void fail_if_not_a_project_permission() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), permissionTemplate.getUuid(), PROVISION_PROJECTS.getKey()); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); assertThatThrownBy(() -> { newRequest(user.getLogin(), permissionTemplate.getUuid(), CODEVIEWER); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_user_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(null, permissionTemplate.getUuid(), CODEVIEWER); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), permissionTemplate.getUuid(), null); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_uuid_and_name_are_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), null, CODEVIEWER); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_user_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> newRequest("unknown-login", permissionTemplate.getUuid(), CODEVIEWER)) .isInstanceOf(NotFoundException.class) .hasMessageContaining("User with login 'unknown-login' is not found"); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), "unknown-key", CODEVIEWER); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String userLogin, @Nullable String templateKey, @Nullable String permission) { TestRequest request = newRequest(); if (userLogin != null) { request.setParam(PARAM_USER_LOGIN, userLogin); } if (templateKey != null) { request.setParam(PARAM_TEMPLATE_ID, templateKey); } if (permission != null) { request.setParam(PARAM_PERMISSION, permission); } request.execute(); } private List<String> getLoginsInTemplateAndPermission(PermissionTemplateDto template, String permission) { PermissionQuery permissionQuery = PermissionQuery.builder().setPermission(permission).build(); return db.getDbClient().permissionTemplateDao() .selectUserLoginsByQueryAndTemplate(db.getSession(), permissionQuery, template.getUuid()); } }
6,952
34.47449
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/ApplyTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class ApplyTemplateActionIT extends BasePermissionWsIT<ApplyTemplateAction> { @Rule public DbTester dbTester = DbTester.create(); private UserDto user1; private UserDto user2; private GroupDto group1; private GroupDto group2; private ProjectDto project; private PermissionTemplateDto template1; private final ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); private final DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbTester.getDbClient(), resourceTypesRule); private final PermissionTemplateService permissionTemplateService = new PermissionTemplateService(db.getDbClient(), new TestIndexers(), userSession, defaultTemplatesResolver, new SequenceUuidFactory()); @Override protected ApplyTemplateAction buildWsAction() { return new ApplyTemplateAction(db.getDbClient(), userSession, permissionTemplateService, newPermissionWsSupport()); } @Before public void setUp() { user1 = db.users().insertUser(); user2 = db.users().insertUser(); group1 = db.users().insertGroup(); group2 = db.users().insertGroup(); // template 1 template1 = db.permissionTemplates().insertTemplate(); addUserToTemplate(user1, template1, UserRole.CODEVIEWER); addUserToTemplate(user2, template1, UserRole.ISSUE_ADMIN); addGroupToTemplate(group1, template1, UserRole.ADMIN); addGroupToTemplate(group2, template1, UserRole.USER); // template 2 PermissionTemplateDto template2 = db.permissionTemplates().insertTemplate(); addUserToTemplate(user1, template2, UserRole.USER); addUserToTemplate(user2, template2, UserRole.USER); addGroupToTemplate(group1, template2, UserRole.USER); addGroupToTemplate(group2, template2, UserRole.USER); project = db.components().insertPrivateProject().getProjectDto(); db.users().insertProjectPermissionOnUser(user1, UserRole.ADMIN, project); db.users().insertProjectPermissionOnUser(user2, UserRole.ADMIN, project); db.users().insertEntityPermissionOnGroup(group1, UserRole.ADMIN, project); db.users().insertEntityPermissionOnGroup(group2, UserRole.ADMIN, project); } @Test public void apply_template_with_project_uuid() { loginAsAdmin(); newRequest(template1.getUuid(), project.getUuid(), null); assertTemplate1AppliedToProject(); } @Test public void apply_template_with_project_uuid_by_template_name() { loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_NAME, template1.getName().toUpperCase()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .execute(); assertTemplate1AppliedToProject(); } @Test public void apply_template_with_project_key() { loginAsAdmin(); newRequest(template1.getUuid(), null, project.getKey()); assertTemplate1AppliedToProject(); } @Test public void fail_when_unknown_template() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest("unknown-template-uuid", project.getUuid(), null); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-template-uuid' is not found"); } @Test public void fail_when_unknown_project_uuid() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(template1.getUuid(), "unknown-project-uuid", null); }) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void fail_when_unknown_project_key() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(template1.getUuid(), null, "unknown-project-key"); }) .isInstanceOf(NotFoundException.class) .hasMessage("Entity not found"); } @Test public void fail_when_template_is_not_provided() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(null, project.getUuid(), null)) .isInstanceOf(BadRequestException.class); } @Test public void fail_when_project_uuid_and_key_not_provided() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(template1.getUuid(), null, null); }) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key can be provided, not both."); } @Test public void fail_when_not_admin() { userSession.logIn().addPermission(SCAN); assertThatThrownBy(() -> newRequest(template1.getUuid(), project.getUuid(), null)) .isInstanceOf(ForbiddenException.class); } private void assertTemplate1AppliedToProject() { assertThat(selectProjectPermissionGroups(project, UserRole.ADMIN)).containsExactly(group1.getName()); assertThat(selectProjectPermissionGroups(project, UserRole.USER)).containsExactly(group2.getName()); assertThat(selectProjectPermissionUsers(project, UserRole.ADMIN)).isEmpty(); assertThat(selectProjectPermissionUsers(project, UserRole.CODEVIEWER)).containsExactly(user1.getUuid()); assertThat(selectProjectPermissionUsers(project, UserRole.ISSUE_ADMIN)).containsExactly(user2.getUuid()); } private void newRequest(@Nullable String templateUuid, @Nullable String projectUuid, @Nullable String projectKey) { TestRequest request = newRequest(); if (templateUuid != null) { request.setParam(PARAM_TEMPLATE_ID, templateUuid); } if (projectUuid != null) { request.setParam(PARAM_PROJECT_ID, projectUuid); } if (projectKey != null) { request.setParam(PARAM_PROJECT_KEY, projectKey); } request.execute(); } private void addUserToTemplate(UserDto user, PermissionTemplateDto permissionTemplate, String permission) { db.getDbClient().permissionTemplateDao().insertUserPermission(db.getSession(), permissionTemplate.getUuid(), user.getUuid(), permission, permissionTemplate.getName(), user.getLogin()); db.commit(); } private void addGroupToTemplate(GroupDto group, PermissionTemplateDto permissionTemplate, String permission) { db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), permissionTemplate.getUuid(), group.getUuid(), permission, permissionTemplate.getName(), group.getName()); db.commit(); } private List<String> selectProjectPermissionGroups(EntityDto entity, String permission) { PermissionQuery query = PermissionQuery.builder().setPermission(permission).setEntity(entity).build(); return db.getDbClient().groupPermissionDao().selectGroupNamesByQuery(db.getSession(), query); } private List<String> selectProjectPermissionUsers(EntityDto entity, String permission) { PermissionQuery query = PermissionQuery.builder().setPermission(permission).setEntity(entity).build(); return db.getDbClient().userPermissionDao().selectUserUuidsByQuery(db.getSession(), query); } }
9,433
38.145228
144
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/BulkApplyTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.Indexers; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.l18n.I18nRule; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.ws.BasePermissionWsIT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.api.utils.DateUtils.parseDate; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY; public class BulkApplyTemplateActionIT extends BasePermissionWsIT<BulkApplyTemplateAction> { private UserDto user1; private UserDto user2; private GroupDto group1; private GroupDto group2; private PermissionTemplateDto template1; private final Indexers indexers = new TestIndexers(); private final ResourceTypesRule resourceTypesRule = new ResourceTypesRule().setRootQualifiers(PROJECT, VIEW, APP); private final DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(db.getDbClient(), resourceTypesRule); @Override protected BulkApplyTemplateAction buildWsAction() { PermissionTemplateService permissionTemplateService = new PermissionTemplateService(db.getDbClient(), indexers, userSession, defaultTemplatesResolver, new SequenceUuidFactory()); return new BulkApplyTemplateAction(db.getDbClient(), userSession, permissionTemplateService, newPermissionWsSupport(), new I18nRule(), newRootResourceTypes()); } @Before public void setUp() { user1 = db.users().insertUser(); user2 = db.users().insertUser(); group1 = db.users().insertGroup(); group2 = db.users().insertGroup(); // template 1 for org 1 template1 = db.permissionTemplates().insertTemplate(); addUserToTemplate(user1, template1, UserRole.CODEVIEWER); addUserToTemplate(user2, template1, UserRole.ISSUE_ADMIN); addGroupToTemplate(group1, template1, UserRole.ADMIN); addGroupToTemplate(group2, template1, UserRole.USER); // template 2 PermissionTemplateDto template2 = db.permissionTemplates().insertTemplate(); addUserToTemplate(user1, template2, UserRole.USER); addUserToTemplate(user2, template2, UserRole.USER); addGroupToTemplate(group1, template2, UserRole.USER); addGroupToTemplate(group2, template2, UserRole.USER); } @Test public void bulk_apply_template_by_template_uuid() { // this project should not be applied the template db.components().insertPrivateProject().getProjectDto(); ProjectDto privateProject = db.components().insertPrivateProject().getProjectDto(); ProjectDto publicProject = db.components().insertPublicProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .execute(); assertTemplate1AppliedToPrivateProject(privateProject); assertTemplate1AppliedToPublicProject(publicProject); } @Test public void request_throws_NotFoundException_if_template_with_specified_name_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_TEMPLATE_NAME, "unknown") .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with name 'unknown' is not found (case insensitive)"); } @Test public void request_throws_IAE_if_more_than_1000_projects() { assertThatThrownBy(() -> { newRequest() .setParam(PARAM_TEMPLATE_NAME, template1.getName()) .setParam(PARAM_PROJECTS, StringUtils.join(Collections.nCopies(1_001, "foo"), ",")) .execute(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'projects' can contains only 1000 values, got 1001"); } @Test public void bulk_apply_template_by_template_name() { ProjectDto privateProject = db.components().insertPrivateProject().getProjectDto(); ProjectDto publicProject = db.components().insertPublicProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_NAME, template1.getName()) .execute(); assertTemplate1AppliedToPrivateProject(privateProject); assertTemplate1AppliedToPublicProject(publicProject); } @Test public void apply_template_by_qualifiers() { ProjectDto publicProject = db.components().insertPublicProject().getProjectDto(); ProjectDto privateProject = db.components().insertPrivateProject().getProjectDto(); PortfolioDto portfolio = db.components().insertPrivatePortfolioDto(); ProjectDto application = db.components().insertPublicApplication().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_QUALIFIERS, String.join(",", Qualifiers.PROJECT, Qualifiers.APP)) .execute(); assertTemplate1AppliedToPrivateProject(privateProject); assertTemplate1AppliedToPublicProject(publicProject); assertTemplate1AppliedToPublicProject(application); assertNoPermissionOnEntity(portfolio); } @Test public void apply_template_by_query_on_name_and_key_public_project() { ComponentDto publicProjectFoundByKey = ComponentTesting.newPublicProjectDto().setKey("sonar"); ProjectDto publicProjectDtoFoundByKey = db.components().insertProjectDataAndSnapshot(publicProjectFoundByKey).getProjectDto(); ComponentDto publicProjectFoundByName = ComponentTesting.newPublicProjectDto().setName("name-sonar-name"); ProjectDto publicProjectDtoFoundByName = db.components().insertProjectDataAndSnapshot(publicProjectFoundByName).getProjectDto(); ComponentDto projectUntouched = ComponentTesting.newPublicProjectDto().setKey("new-sona").setName("project-name"); ProjectDto projectDtoUntouched = db.components().insertProjectDataAndSnapshot(projectUntouched).getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(Param.TEXT_QUERY, "SONAR") .execute(); assertTemplate1AppliedToPublicProject(publicProjectDtoFoundByKey); assertTemplate1AppliedToPublicProject(publicProjectDtoFoundByName); assertNoPermissionOnEntity(projectDtoUntouched); } @Test public void apply_template_by_query_on_name_and_key() { // partial match on key ComponentDto privateProjectFoundByKey = ComponentTesting.newPrivateProjectDto().setKey("sonarqube"); ProjectDto privateProjectDtoFoundByKey = db.components().insertProjectDataAndSnapshot(privateProjectFoundByKey).getProjectDto(); ComponentDto privateProjectFoundByName = ComponentTesting.newPrivateProjectDto().setName("name-sonar-name"); ProjectDto privateProjectDtoFoundByName = db.components().insertProjectDataAndSnapshot(privateProjectFoundByName).getProjectDto(); ComponentDto projectUntouched = ComponentTesting.newPublicProjectDto().setKey("new-sona").setName("project-name"); ProjectDto projectDtoUntouched = db.components().insertProjectDataAndSnapshot(projectUntouched).getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(Param.TEXT_QUERY, "SONAR") .execute(); assertTemplate1AppliedToPrivateProject(privateProjectDtoFoundByKey); assertTemplate1AppliedToPrivateProject(privateProjectDtoFoundByName); assertNoPermissionOnEntity(projectDtoUntouched); } @Test public void apply_template_by_project_keys() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); ProjectDto untouchedProject = db.components().insertPrivateProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_PROJECTS, String.join(",", project1.getKey(), project2.getKey())) .execute(); assertTemplate1AppliedToPrivateProject(project1); assertTemplate1AppliedToPrivateProject(project2); assertNoPermissionOnEntity(untouchedProject); } @Test public void apply_template_by_provisioned_only() { ProjectDto provisionedProject1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto provisionedProject2 = db.components().insertPrivateProject().getProjectDto(); ProjectData analyzedProject = db.components().insertPrivateProject(); db.components().insertSnapshot(newAnalysis(analyzedProject.getMainBranchDto().getUuid())); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_ON_PROVISIONED_ONLY, "true") .execute(); assertTemplate1AppliedToPrivateProject(provisionedProject1); assertTemplate1AppliedToPrivateProject(provisionedProject2); assertNoPermissionOnEntity(analyzedProject.getProjectDto()); } @Test public void apply_template_by_analyzed_before() { ProjectData oldProject1 = db.components().insertPrivateProject(); ProjectData oldProject2 = db.components().insertPrivateProject(); ProjectData recentProject = db.components().insertPrivateProject(); db.components().insertSnapshot(oldProject1.getMainBranchComponent(), a -> a.setCreatedAt(parseDate("2015-02-03").getTime())); db.components().insertSnapshot(oldProject2.getMainBranchComponent(), a -> a.setCreatedAt(parseDate("2016-12-11").getTime())); db.components().insertSnapshot(recentProject.getMainBranchComponent(), a -> a.setCreatedAt(System.currentTimeMillis())); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_ANALYZED_BEFORE, "2017-09-07") .execute(); assertTemplate1AppliedToPrivateProject(oldProject1.getProjectDto()); assertTemplate1AppliedToPrivateProject(oldProject2.getProjectDto()); assertNoPermissionOnEntity(recentProject.getProjectDto()); } @Test public void apply_template_by_visibility() { ProjectDto privateProject1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto privateProject2 = db.components().insertPrivateProject().getProjectDto(); ProjectDto publicProject = db.components().insertPublicProject().getProjectDto(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_VISIBILITY, "private") .execute(); assertTemplate1AppliedToPrivateProject(privateProject1); assertTemplate1AppliedToPrivateProject(privateProject2); assertNoPermissionOnEntity(publicProject); } @Test public void fail_if_no_template_parameter() { loginAsAdmin(); assertThatThrownBy(() -> newRequest().execute()) .isInstanceOf(BadRequestException.class) .hasMessage("Template name or template id must be provided, not both."); } @Test public void fail_if_template_name_is_incorrect() { loginAsAdmin(); assertThatThrownBy(() -> newRequest().setParam(PARAM_TEMPLATE_ID, "unknown-template-uuid").execute()) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-template-uuid' is not found"); } private void assertTemplate1AppliedToPublicProject(ProjectDto project) { assertThat(selectProjectPermissionGroups(project, UserRole.ADMIN)).containsExactly(group1.getName()); assertThat(selectProjectPermissionGroups(project, UserRole.USER)).isEmpty(); assertThat(selectProjectPermissionUsers(project, UserRole.ADMIN)).isEmpty(); assertThat(selectProjectPermissionUsers(project, UserRole.CODEVIEWER)).isEmpty(); assertThat(selectProjectPermissionUsers(project, UserRole.ISSUE_ADMIN)).containsExactly(user2.getUuid()); } private void assertTemplate1AppliedToPrivateProject(ProjectDto project) { assertThat(selectProjectPermissionGroups(project, UserRole.ADMIN)).containsExactly(group1.getName()); assertThat(selectProjectPermissionGroups(project, UserRole.USER)).containsExactly(group2.getName()); assertThat(selectProjectPermissionUsers(project, UserRole.ADMIN)).isEmpty(); assertThat(selectProjectPermissionUsers(project, UserRole.CODEVIEWER)).containsExactly(user1.getUuid()); assertThat(selectProjectPermissionUsers(project, UserRole.ISSUE_ADMIN)).containsExactly(user2.getUuid()); } private void assertNoPermissionOnEntity(EntityDto entity) { assertThat(selectProjectPermissionGroups(entity, UserRole.ADMIN)).isEmpty(); assertThat(selectProjectPermissionGroups(entity, UserRole.CODEVIEWER)).isEmpty(); assertThat(selectProjectPermissionGroups(entity, UserRole.ISSUE_ADMIN)).isEmpty(); assertThat(selectProjectPermissionGroups(entity, UserRole.USER)).isEmpty(); assertThat(selectProjectPermissionUsers(entity, UserRole.ADMIN)).isEmpty(); assertThat(selectProjectPermissionUsers(entity, UserRole.CODEVIEWER)).isEmpty(); assertThat(selectProjectPermissionUsers(entity, UserRole.ISSUE_ADMIN)).isEmpty(); assertThat(selectProjectPermissionUsers(entity, UserRole.USER)).isEmpty(); } private void addUserToTemplate(UserDto user, PermissionTemplateDto permissionTemplate, String permission) { db.getDbClient().permissionTemplateDao().insertUserPermission(db.getSession(), permissionTemplate.getUuid(), user.getUuid(), permission, permissionTemplate.getName(), user.getLogin()); db.commit(); } private void addGroupToTemplate(GroupDto group, PermissionTemplateDto permissionTemplate, String permission) { db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), permissionTemplate.getUuid(), group.getUuid(), permission, permissionTemplate.getName(), group.getName()); db.commit(); } private List<String> selectProjectPermissionGroups(EntityDto project, String permission) { PermissionQuery query = PermissionQuery.builder().setPermission(permission).setEntity(project).build(); return db.getDbClient().groupPermissionDao().selectGroupNamesByQuery(db.getSession(), query); } private List<String> selectProjectPermissionUsers(EntityDto project, String permission) { PermissionQuery query = PermissionQuery.builder().setPermission(permission).setEntity(project).build(); return db.getDbClient().userPermissionDao().selectUserUuidsByQuery(db.getSession(), query); } }
16,928
45.894737
163
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/CreateTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.utils.System2; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN; public class CreateTemplateActionIT extends BasePermissionWsIT<CreateTemplateAction> { private static final long NOW = 1_440_512_328_743L; private final System2 system = new TestSystem2().setNow(NOW); @Override protected CreateTemplateAction buildWsAction() { return new CreateTemplateAction(db.getDbClient(), userSession, system); } @Test public void create_full_permission_template() { loginAsAdmin(); TestResponse result = newRequest("Finance", "Permissions for financially related projects", ".*\\.finance\\..*"); assertJson(result.getInput()) .ignoreFields("id") .isSimilarTo(getClass().getResource("create_template-example.json")); PermissionTemplateDto finance = selectPermissionTemplate("Finance"); assertThat(finance.getName()).isEqualTo("Finance"); assertThat(finance.getDescription()).isEqualTo("Permissions for financially related projects"); assertThat(finance.getKeyPattern()).isEqualTo(".*\\.finance\\..*"); assertThat(finance.getUuid()).isNotEmpty(); assertThat(finance.getCreatedAt().getTime()).isEqualTo(NOW); assertThat(finance.getUpdatedAt().getTime()).isEqualTo(NOW); } @Test public void create_minimalist_permission_template() { loginAsAdmin(); newRequest("Finance", null, null); PermissionTemplateDto finance = selectPermissionTemplate("Finance"); assertThat(finance.getName()).isEqualTo("Finance"); assertThat(finance.getDescription()).isNullOrEmpty(); assertThat(finance.getKeyPattern()).isNullOrEmpty(); assertThat(finance.getUuid()).isNotEmpty(); assertThat(finance.getCreatedAt().getTime()).isEqualTo(NOW); assertThat(finance.getUpdatedAt().getTime()).isEqualTo(NOW); } @Test public void fail_if_name_not_provided() { loginAsAdmin(); assertThatThrownBy(() -> newRequest(null, null, null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_name_empty() { loginAsAdmin(); assertThatThrownBy(() -> newRequest("", null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'name' parameter is missing"); } @Test public void fail_if_regexp_if_not_valid() { loginAsAdmin(); assertThatThrownBy(() -> newRequest("Finance", null, "[azerty")) .isInstanceOf(BadRequestException.class) .hasMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); } @Test public void fail_if_name_already_exists_in_database_case_insensitive() { loginAsAdmin(); PermissionTemplateDto template = db.permissionTemplates().insertTemplate(); assertThatThrownBy(() -> newRequest(template.getName(), null, null)) .isInstanceOf(BadRequestException.class) .hasMessage("A template with the name '" + template.getName() + "' already exists (case insensitive)."); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); assertThatThrownBy(() -> newRequest("Finance", null, null)) .isInstanceOf(ForbiddenException.class); } private TestResponse newRequest(@Nullable String name, @Nullable String description, @Nullable String projectPattern) { TestRequest request = newRequest(); if (name != null) { request.setParam(PARAM_NAME, name); } if (description != null) { request.setParam(PARAM_DESCRIPTION, description); } if (projectPattern != null) { request.setParam(PARAM_PROJECT_KEY_PATTERN, projectPattern); } return request.execute(); } }
5,462
37.202797
121
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/DeleteTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.GroupTesting; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.ws.PermissionWsSupport; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.usergroups.ws.GroupWsSupport; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class DeleteTemplateActionIT { @Rule public DbTester db = DbTester.create(new AlwaysIncreasingSystem2()); private final UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT, APP, VIEW); private final DefaultTemplatesResolver defaultTemplatesResolver = new DefaultTemplatesResolverImpl(dbClient, resourceTypes); private final Configuration configuration = mock(Configuration.class); private WsActionTester underTest; @Before public void setUp() { GroupWsSupport groupWsSupport = new GroupWsSupport(dbClient, new DefaultGroupFinder(db.getDbClient())); this.underTest = new WsActionTester(new DeleteTemplateAction(dbClient, userSession, new PermissionWsSupport(dbClient, configuration, new ComponentFinder(dbClient, resourceTypes), groupWsSupport), defaultTemplatesResolver)); } @Test public void delete_template_in_db() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); PermissionTemplateDto projectPermissionTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto portfolioPermissionTemplate = db.permissionTemplates().insertTemplate(); db.permissionTemplates().setDefaultTemplates(projectPermissionTemplate, null, portfolioPermissionTemplate); loginAsAdmin(); TestResponse result = newRequestByUuid(underTest, template.getUuid()); assertThat(result.getInput()).isEmpty(); assertTemplateDoesNotExist(template); } @Test public void delete_template_by_name_case_insensitive() { db.permissionTemplates().setDefaultTemplates( db.permissionTemplates().insertTemplate().getUuid(), db.permissionTemplates().insertTemplate().getUuid(), db.permissionTemplates().insertTemplate().getUuid()); PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); loginAsAdmin(); newRequestByName(underTest, template); assertTemplateDoesNotExist(template); } @Test public void fail_if_uuid_is_not_known() { userSession.logIn(); assertThatThrownBy(() -> newRequestByUuid(underTest, "unknown-template-uuid")) .isInstanceOf(NotFoundException.class); } @Test public void fail_to_delete_by_uuid_if_template_is_default_template() { PermissionTemplateDto projectTemplate = insertTemplateAndAssociatedPermissions(); db.permissionTemplates().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); assertThatThrownBy(() -> newRequestByUuid(underTest, projectTemplate.getUuid())) .isInstanceOf(BadRequestException.class) .hasMessage("It is not possible to delete the default permission template for projects"); } @Test public void fail_to_delete_by_name_if_template_is_default_template_for_project() { PermissionTemplateDto projectTemplate = insertTemplateAndAssociatedPermissions(); db.permissionTemplates().setDefaultTemplates(projectTemplate, null, db.permissionTemplates().insertTemplate()); loginAsAdmin(); assertThatThrownBy(() -> newRequestByName(underTest, projectTemplate.getName())) .isInstanceOf(BadRequestException.class) .hasMessage("It is not possible to delete the default permission template for projects"); } @Test public void fail_to_delete_by_uuid_if_template_is_default_template_for_portfolios() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, template); loginAsAdmin(); assertThatThrownBy(() -> newRequestByUuid(this.underTest, template.getUuid())) .isInstanceOf(BadRequestException.class) .hasMessage("It is not possible to delete the default permission template for portfolios"); } @Test public void fail_to_delete_by_uuid_if_template_is_default_template_for_applications() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), template, null); loginAsAdmin(); assertThatThrownBy(() -> newRequestByUuid(this.underTest, template.getUuid())) .isInstanceOf(BadRequestException.class) .hasMessage("It is not possible to delete the default permission template for applications"); } @Test public void fail_to_delete_by_uuid_if_not_logged_in() { assertThatThrownBy(() -> newRequestByUuid(underTest, "uuid")) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_to_delete_by_name_if_not_logged_in() { assertThatThrownBy(() -> newRequestByName(underTest, "name")) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_to_delete_by_uuid_if_not_admin() { PermissionTemplateDto template = insertTemplateAndAssociatedPermissions(); userSession.logIn(); assertThatThrownBy(() -> newRequestByUuid(underTest, template.getUuid())) .isInstanceOf(ForbiddenException.class); } @Test public void fail_to_delete_by_name_if_not_admin() { PermissionTemplateDto template = db.permissionTemplates().insertTemplate(); userSession.logIn(); assertThatThrownBy(() -> newRequestByName(underTest, template.getName())) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_neither_uuid_nor_name_is_provided() { userSession.logIn(); assertThatThrownBy(() -> newRequestByUuid(underTest, null)) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_both_uuid_and_name_are_provided() { userSession.logIn(); assertThatThrownBy(() -> { underTest.newRequest().setMethod("POST") .setParam(PARAM_TEMPLATE_ID, "uuid") .setParam(PARAM_TEMPLATE_NAME, "name") .execute(); }) .isInstanceOf(BadRequestException.class); } private UserSessionRule loginAsAdmin() { return userSession.logIn().addPermission(ADMINISTER); } private PermissionTemplateDto insertTemplateAndAssociatedPermissions() { PermissionTemplateDto dto = db.permissionTemplates().insertTemplate(); UserDto user = db.getDbClient().userDao().insert(db.getSession(), UserTesting.newUserDto().setActive(true)); GroupDto group = db.getDbClient().groupDao().insert(db.getSession(), GroupTesting.newGroupDto()); db.getDbClient().permissionTemplateDao().insertUserPermission(db.getSession(), dto.getUuid(), user.getUuid(), UserRole.ADMIN, dto.getName(), user.getLogin()); db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), dto.getUuid(), group.getUuid(), UserRole.CODEVIEWER, dto.getName(), group.getName()); db.commit(); return dto; } private TestResponse newRequestByUuid(WsActionTester actionTester, @Nullable String id) { TestRequest request = actionTester.newRequest().setMethod("POST"); if (id != null) { request.setParam(PARAM_TEMPLATE_ID, id); } return request.execute(); } private void newRequestByName(WsActionTester actionTester, @Nullable PermissionTemplateDto permissionTemplateDto) { newRequestByName( actionTester, permissionTemplateDto == null ? null : permissionTemplateDto.getName()); } private TestResponse newRequestByName(WsActionTester actionTester, @Nullable String name) { TestRequest request = actionTester.newRequest().setMethod("POST"); if (name != null) { request.setParam(PARAM_TEMPLATE_NAME, name); } return request.execute(); } private void assertTemplateDoesNotExist(PermissionTemplateDto template) { assertThat(db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), template.getUuid())).isNull(); } }
10,622
40.174419
145
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/RemoveGroupFromTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService.Action; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.security.DefaultGroups.ANYONE; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class RemoveGroupFromTemplateActionIT extends BasePermissionWsIT<RemoveGroupFromTemplateAction> { private static final String PERMISSION = CODEVIEWER; private GroupDto group; private PermissionTemplateDto template; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); @Override protected RemoveGroupFromTemplateAction buildWsAction() { return new RemoveGroupFromTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, wsParameters); } @Before public void setUp() { loginAsAdmin(); group = db.users().insertGroup("group-name"); template = db.permissionTemplates().insertTemplate(); addGroupToTemplate(template, group.getUuid(), PERMISSION, group.getName()); } @Test public void verify_definition() { Action wsDef = wsTester.getDef(); assertThat(wsDef.isInternal()).isFalse(); assertThat(wsDef.since()).isEqualTo("5.2"); assertThat(wsDef.isPost()).isTrue(); assertThat(wsDef.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly( tuple("10.0", "Parameter 'groupId' is removed. Use 'groupName' instead."), tuple("8.4", "Parameter 'groupId' is deprecated. Format changes from integer to string. Use 'groupName' instead.")); } @Test public void remove_group_from_template() { newRequest(group.getName(), template.getUuid(), PERMISSION); assertThat(getGroupNamesInTemplateAndPermission(template, PERMISSION)).isEmpty(); } @Test public void remove_group_from_template_by_name_case_insensitive() { newRequest() .setParam(PARAM_GROUP_NAME, group.getName()) .setParam(PARAM_PERMISSION, PERMISSION) .setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase()) .execute(); assertThat(getGroupNamesInTemplateAndPermission(template, PERMISSION)).isEmpty(); } @Test public void remove_group_twice_without_error() { newRequest(group.getName(), template.getUuid(), PERMISSION); newRequest(group.getName(), template.getUuid(), PERMISSION); assertThat(getGroupNamesInTemplateAndPermission(template, PERMISSION)).isEmpty(); } @Test public void remove_anyone_group_from_template() { addGroupToTemplate(template, null, PERMISSION, null); newRequest(ANYONE, template.getUuid(), PERMISSION); assertThat(getGroupNamesInTemplateAndPermission(template, PERMISSION)).containsExactly(group.getName()); } @Test public void fail_if_not_a_project_permission() { assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), PROVISION_PROJECTS.getKey())) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn().addPermission(SCAN); assertThatThrownBy(() -> newRequest(group.getName(), template.getUuid(), PERMISSION)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { assertThatThrownBy(() -> { userSession.anonymous(); newRequest(group.getName(), template.getUuid(), PERMISSION); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_group_params_missing() { assertThatThrownBy(() -> { newRequest(null, template.getUuid(), PERMISSION); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'groupName' parameter is missing"); } @Test public void fail_if_permission_missing() { assertThatThrownBy(() -> { newRequest(group.getName(), template.getUuid(), null); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_missing() { assertThatThrownBy(() -> { newRequest(group.getName(), null, PERMISSION); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_group_does_not_exist() { assertThatThrownBy(() -> { newRequest("unknown-group-name", template.getUuid(), PERMISSION); }) .isInstanceOf(NotFoundException.class) .hasMessage("No group with name 'unknown-group-name'"); } @Test public void fail_if_template_key_does_not_exist() { assertThatThrownBy(() -> { newRequest(group.getName(), "unknown-key", PERMISSION); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String groupName, @Nullable String templateKey, @Nullable String permission) { TestRequest request = newRequest(); if (groupName != null) { request.setParam(PARAM_GROUP_NAME, groupName); } if (templateKey != null) { request.setParam(PARAM_TEMPLATE_ID, templateKey); } if (permission != null) { request.setParam(PARAM_PERMISSION, permission); } request.execute(); } private void addGroupToTemplate(PermissionTemplateDto template, @Nullable String groupUuid, String permission, String groupName) { db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), template.getUuid(), groupUuid, permission, template.getName(), groupName); db.commit(); } private List<String> getGroupNamesInTemplateAndPermission(PermissionTemplateDto template, String permission) { PermissionQuery permissionQuery = PermissionQuery.builder().setPermission(permission).build(); return db.getDbClient().permissionTemplateDao() .selectGroupNamesByQueryAndTemplate(db.getSession(), permissionQuery, template.getUuid()); } }
8,369
37.045455
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/RemoveProjectCreatorFromTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class RemoveProjectCreatorFromTemplateActionIT extends BasePermissionWsIT<RemoveProjectCreatorFromTemplateAction> { private System2 system = mock(System2.class); private PermissionTemplateDto template; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); private RequestValidator requestValidator = new RequestValidator(permissionService); @Override protected RemoveProjectCreatorFromTemplateAction buildWsAction() { return new RemoveProjectCreatorFromTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, system, wsParameters, requestValidator); } @Before public void setUp() { loginAsAdmin(); when(system.now()).thenReturn(2_000_000_000L); template = db.permissionTemplates().insertTemplate(); } @Test public void update_template_permission() { PermissionTemplateCharacteristicDto characteristic = db.getDbClient().permissionTemplateCharacteristicDao().insert(db.getSession(), new PermissionTemplateCharacteristicDto() .setUuid(Uuids.createFast()) .setTemplateUuid(template.getUuid()) .setPermission(UserRole.USER) .setWithProjectCreator(false) .setCreatedAt(1_000_000_000L) .setUpdatedAt(1_000_000_000L), template.getName()); db.commit(); when(system.now()).thenReturn(3_000_000_000L); newRequest() .setParam(PARAM_PERMISSION, UserRole.USER) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .execute(); assertWithoutProjectCreatorFor(UserRole.USER); PermissionTemplateCharacteristicDto reloaded = reload(characteristic); assertThat(reloaded.getCreatedAt()).isEqualTo(1_000_000_000L); assertThat(reloaded.getUpdatedAt()).isEqualTo(3_000_000_000L); } @Test public void do_not_fail_when_no_template_permission() { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); assertNoTemplatePermissionFor(UserRole.ADMIN); } @Test public void fail_when_template_does_not_exist() { assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, "42") .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_permission_is_not_a_project_permission() { assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, ADMINISTER_QUALITY_GATES.getKey()) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_not_authenticated() { userSession.anonymous(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, UserRole.ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute(); }) .isInstanceOf(ForbiddenException.class); } private void assertWithoutProjectCreatorFor(String permission) { Optional<PermissionTemplateCharacteristicDto> templatePermission = db.getDbClient().permissionTemplateCharacteristicDao().selectByPermissionAndTemplateId(db.getSession(), permission, template.getUuid()); assertThat(templatePermission).isPresent(); assertThat(templatePermission.get().getWithProjectCreator()).isFalse(); } private void assertNoTemplatePermissionFor(String permission) { Optional<PermissionTemplateCharacteristicDto> templatePermission = db.getDbClient().permissionTemplateCharacteristicDao().selectByPermissionAndTemplateId(db.getSession(), permission, template.getUuid()); assertThat(templatePermission).isNotPresent(); } private PermissionTemplateCharacteristicDto reload(PermissionTemplateCharacteristicDto characteristic) { return db.getDbClient().permissionTemplateCharacteristicDao().selectByPermissionAndTemplateId(db.getSession(), characteristic.getPermission(), characteristic.getTemplateUuid()) .get(); } }
6,893
38.849711
180
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/RemoveUserFromTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.List; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.PermissionQuery; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_USER_LOGIN; public class RemoveUserFromTemplateActionIT extends BasePermissionWsIT<RemoveUserFromTemplateAction> { private static final String DEFAULT_PERMISSION = CODEVIEWER; private UserDto user; private PermissionTemplateDto template; private ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private WsParameters wsParameters = new WsParameters(permissionService); private RequestValidator requestValidator = new RequestValidator(permissionService); @Override protected RemoveUserFromTemplateAction buildWsAction() { return new RemoveUserFromTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession, wsParameters, requestValidator); } @Before public void setUp() { user = db.users().insertUser("user-login"); template = db.permissionTemplates().insertTemplate(); addUserToTemplate(user, template, DEFAULT_PERMISSION); } @Test public void remove_user_from_template() { loginAsAdmin(); newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); assertThat(getLoginsInTemplateAndPermission(template, DEFAULT_PERMISSION)).isEmpty(); } @Test public void remove_user_from_template_by_name_case_insensitive() { loginAsAdmin(); newRequest() .setParam(PARAM_USER_LOGIN, user.getLogin()) .setParam(PARAM_PERMISSION, DEFAULT_PERMISSION) .setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase()) .execute(); assertThat(getLoginsInTemplateAndPermission(template, DEFAULT_PERMISSION)).isEmpty(); } @Test public void remove_user_from_template_twice_without_failing() { loginAsAdmin(); newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); assertThat(getLoginsInTemplateAndPermission(template, DEFAULT_PERMISSION)).isEmpty(); } @Test public void keep_user_permission_not_removed() { addUserToTemplate(user, template, ISSUE_ADMIN); loginAsAdmin(); newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); assertThat(getLoginsInTemplateAndPermission(template, DEFAULT_PERMISSION)).isEmpty(); assertThat(getLoginsInTemplateAndPermission(template, ISSUE_ADMIN)).containsExactly(user.getLogin()); } @Test public void keep_other_users_when_one_user_removed() { UserDto newUser = db.users().insertUser("new-login"); addUserToTemplate(newUser, template, DEFAULT_PERMISSION); loginAsAdmin(); newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); assertThat(getLoginsInTemplateAndPermission(template, DEFAULT_PERMISSION)).containsExactly("new-login"); } @Test public void fail_if_not_a_project_permission() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), template.getUuid(), PROVISION_PROJECTS.getKey()); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_insufficient_privileges() { userSession.logIn(); assertThatThrownBy(() -> { newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_logged_in() { userSession.anonymous(); assertThatThrownBy(() -> { newRequest(user.getLogin(), template.getUuid(), DEFAULT_PERMISSION); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_user_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(null, template.getUuid(), DEFAULT_PERMISSION); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_permission_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), template.getUuid(), null); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_template_missing() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), null, DEFAULT_PERMISSION); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_user_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> newRequest("unknown-login", template.getUuid(), DEFAULT_PERMISSION)) .isInstanceOf(NotFoundException.class) .hasMessageContaining("User with login 'unknown-login' is not found"); } @Test public void fail_if_template_key_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(user.getLogin(), "unknown-key", DEFAULT_PERMISSION); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-key' is not found"); } private void newRequest(@Nullable String userLogin, @Nullable String templateKey, @Nullable String permission) { TestRequest request = newRequest(); if (userLogin != null) { request.setParam(PARAM_USER_LOGIN, userLogin); } if (templateKey != null) { request.setParam(PARAM_TEMPLATE_ID, templateKey); } if (permission != null) { request.setParam(PARAM_PERMISSION, permission); } request.execute(); } private List<String> getLoginsInTemplateAndPermission(PermissionTemplateDto template, String permission) { PermissionQuery permissionQuery = PermissionQuery.builder().setPermission(permission).build(); return db.getDbClient().permissionTemplateDao() .selectUserLoginsByQueryAndTemplate(db.getSession(), permissionQuery, template.getUuid()); } private void addUserToTemplate(UserDto user, PermissionTemplateDto template, String permission) { db.getDbClient().permissionTemplateDao().insertUserPermission(db.getSession(), template.getUuid(), user.getUuid(), permission, template.getName(), user.getLogin()); db.commit(); } }
8,453
34.974468
133
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/SearchTemplatesActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.Date; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateCharacteristicDto; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.l18n.I18nRule; import org.sonar.server.permission.DefaultTemplatesResolver; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02; import static org.sonar.core.util.Uuids.UUID_EXAMPLE_10; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; import static org.sonar.test.JsonAssert.assertJson; public class SearchTemplatesActionIT extends BasePermissionWsIT<SearchTemplatesAction> { private I18nRule i18n = new I18nRule(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private ResourceTypesRule resourceTypesWithViews = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); private ResourceTypesRule resourceTypesWithoutViews = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private PermissionService permissionServiceWithViews = new PermissionServiceImpl(resourceTypesWithViews); private PermissionService permissionServiceWithoutViews = new PermissionServiceImpl(resourceTypesWithoutViews); private DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(dbClient, resourceTypesWithViews); private WsActionTester underTestWithoutViews; @Override protected SearchTemplatesAction buildWsAction() { return new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithViews); } @Before public void setUp() { DefaultTemplatesResolver defaultTemplatesResolverWithViews = new DefaultTemplatesResolverImpl(dbClient, resourceTypesWithoutViews); underTestWithoutViews = new WsActionTester( new SearchTemplatesAction(dbClient, userSession, i18n, defaultTemplatesResolverWithViews, permissionServiceWithoutViews)); i18n.setProjectPermissions(); userSession.logIn().addPermission(ADMINISTER); } @Test public void search_project_permissions_without_views() { PermissionTemplateDto projectTemplate = insertProjectTemplate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); UserDto user3 = db.users().insertUser(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); GroupDto group3 = db.users().insertGroup(); addUserToTemplate(projectTemplate.getUuid(), user1.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user1.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user2.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user2.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user3.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user3.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user1.getUuid(), UserRole.CODEVIEWER, projectTemplate.getName(), user1.getLogin()); addGroupToTemplate(projectTemplate.getUuid(), group1.getUuid(), UserRole.ADMIN, projectTemplate.getName(), group1.getName()); addPermissionTemplateWithProjectCreator(projectTemplate.getUuid(), UserRole.ADMIN, projectTemplate.getName()); db.permissionTemplates().setDefaultTemplates(projectTemplate, null, null); String result = newRequest(underTestWithoutViews).execute().getInput(); assertJson(result) .withStrictArrayOrder() .isSimilarTo(getClass().getResource("search_templates-example-without-views.json")); } @Test public void search_project_permissions_with_views() { PermissionTemplateDto projectTemplate = insertProjectTemplate(); PermissionTemplateDto portfoliosTemplate = insertPortfoliosTemplate(); PermissionTemplateDto applicationsTemplate = insertApplicationsTemplate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); UserDto user3 = db.users().insertUser(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); GroupDto group3 = db.users().insertGroup(); addUserToTemplate(projectTemplate.getUuid(), user1.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user1.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user2.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user2.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user3.getUuid(), UserRole.ISSUE_ADMIN, projectTemplate.getName(), user3.getLogin()); addUserToTemplate(projectTemplate.getUuid(), user1.getUuid(), UserRole.CODEVIEWER, projectTemplate.getName(), user1.getLogin()); addGroupToTemplate(projectTemplate.getUuid(), group1.getUuid(), UserRole.ADMIN, projectTemplate.getName(), group1.getName()); addPermissionTemplateWithProjectCreator(projectTemplate.getUuid(), UserRole.ADMIN, projectTemplate.getName()); addUserToTemplate(portfoliosTemplate.getUuid(), user1.getUuid(), UserRole.USER, portfoliosTemplate.getName(), user1.getLogin()); addUserToTemplate(portfoliosTemplate.getUuid(), user2.getUuid(), UserRole.USER, portfoliosTemplate.getName(), user2.getLogin()); addGroupToTemplate(portfoliosTemplate.getUuid(), group1.getUuid(), UserRole.ISSUE_ADMIN, portfoliosTemplate.getName(), group1.getName()); addGroupToTemplate(portfoliosTemplate.getUuid(), group2.getUuid(), UserRole.ISSUE_ADMIN, portfoliosTemplate.getName(), group2.getName()); addGroupToTemplate(portfoliosTemplate.getUuid(), group3.getUuid(), UserRole.ISSUE_ADMIN, portfoliosTemplate.getName(), group3.getName()); db.permissionTemplates().setDefaultTemplates(projectTemplate, applicationsTemplate, portfoliosTemplate); String result = newRequest().execute().getInput(); assertJson(result) .withStrictArrayOrder() .isSimilarTo(getClass().getResource("search_templates-example-with-views.json")); } @Test public void empty_result() { db.permissionTemplates().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-Tpxb--iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); String result = newRequest(wsTester).execute().getInput(); assertJson(result) .withStrictArrayOrder() .ignoreFields("permissions") .isSimilarTo("{" + " \"permissionTemplates\": []," + " \"defaultTemplates\": [" + " {" + " \"templateId\": \"AU-Tpxb--iU5OvuD2FLy\"," + " \"qualifier\": \"TRK\"" + " }," + " {" + " \"templateId\": \"AU-Tpxb--iU5OvuD2FLz\"," + " \"qualifier\": \"APP\"" + " }," + " {" + " \"templateId\": \"AU-TpxcA-iU5OvuD2FLx\"," + " \"qualifier\": \"VW\"" + " }" + " ]" + "}"); } @Test public void empty_result_without_views() { db.permissionTemplates().setDefaultTemplates("AU-Tpxb--iU5OvuD2FLy", "AU-TpxcA-iU5OvuD2FLz", "AU-TpxcA-iU5OvuD2FLx"); String result = newRequest(underTestWithoutViews).execute().getInput(); assertJson(result) .withStrictArrayOrder() .ignoreFields("permissions") .isSimilarTo("{" + " \"permissionTemplates\": []," + " \"defaultTemplates\": [" + " {" + " \"templateId\": \"AU-Tpxb--iU5OvuD2FLy\"," + " \"qualifier\": \"TRK\"" + " }" + " ]" + "}"); } @Test public void search_by_name() { db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); insertProjectTemplate(); insertPortfoliosTemplate(); String result = newRequest(wsTester) .setParam(TEXT_QUERY, "portfolio") .execute() .getInput(); assertThat(result).contains("Default template for Portfolios") .doesNotContain("projects") .doesNotContain("developers"); } @Test public void fail_if_not_logged_in() { assertThatThrownBy(() -> { userSession.anonymous(); newRequest().execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void display_all_project_permissions() { db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); String result = newRequest(underTestWithoutViews).execute().getInput(); assertJson(result) .withStrictArrayOrder() .ignoreFields("defaultTemplates", "permissionTemplates") .isSimilarTo( "{" + " \"permissions\": [" + " {" + " \"key\": \"admin\"," + " \"name\": \"Administer\"," + " \"description\": \"Ability to access project settings and perform administration tasks. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"codeviewer\"," + " \"name\": \"See Source Code\"," + " \"description\": \"Ability to view the project\\u0027s source code. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"issueadmin\"," + " \"name\": \"Administer Issues\"," + " \"description\": \"Grants the permission to perform advanced editing on issues: marking an issue False Positive / Won\\u0027t Fix or changing an Issue\\u0027s severity. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"securityhotspotadmin\"," + " \"name\": \"Administer Security Hotspots\"," + " \"description\": \"Detect a Vulnerability from a \\\"Security Hotspot\\\". Reject, clear, accept, reopen a \\\"Security Hotspot\\\" (users also need \\\"Browse\\\" permissions).\"" + " }," + " {" + " \"key\": \"scan\"," + " \"name\": \"Execute Analysis\"," + " \"description\": \"Ability to execute analyses, and to get all settings required to perform the analysis, even the secured ones like the scm account password, the jira account password, and so on.\"" + " }," + " {" + " \"key\": \"user\"," + " \"name\": \"Browse\"," + " \"description\": \"Ability to access a project, browse its measures, and create/edit issues for it.\"" + " }" + " ]" + "}"); } @Test public void display_all_project_permissions_with_views() { db.permissionTemplates().setDefaultTemplates(db.permissionTemplates().insertTemplate(), null, null); String result = newRequest().execute().getInput(); assertJson(result) .withStrictArrayOrder() .ignoreFields("defaultTemplates", "permissionTemplates") .isSimilarTo( "{" + " \"permissions\": [" + " {" + " \"key\": \"admin\"," + " \"name\": \"Administer\"," + " \"description\": \"Ability to access project settings and perform administration tasks. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"codeviewer\"," + " \"name\": \"See Source Code\"," + " \"description\": \"Ability to view the project\\u0027s source code. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"issueadmin\"," + " \"name\": \"Administer Issues\"," + " \"description\": \"Grants the permission to perform advanced editing on issues: marking an issue False Positive / Won\\u0027t Fix or changing an Issue\\u0027s severity. (Users will also need \\\"Browse\\\" permission)\"" + " }," + " {" + " \"key\": \"securityhotspotadmin\"," + " \"name\": \"Administer Security Hotspots\"," + " \"description\": \"Detect a Vulnerability from a \\\"Security Hotspot\\\". Reject, clear, accept, reopen a \\\"Security Hotspot\\\" (users also need \\\"Browse\\\" permissions).\"" + " }," + " {" + " \"key\": \"scan\"," + " \"name\": \"Execute Analysis\"," + " \"description\": \"Ability to execute analyses, and to get all settings required to perform the analysis, even the secured ones like the scm account password, the jira account password, and so on.\"" + " }," + " {" + " \"key\": \"user\"," + " \"name\": \"Browse\"," + " \"description\": \"Ability to access a project, browse its measures, and create/edit issues for it.\"" + " }" + " ]" + "}"); } private PermissionTemplateDto insertProjectTemplate() { return insertProjectTemplate(UUID_EXAMPLE_01); } private PermissionTemplateDto insertProjectTemplate(String uuid) { return insertTemplate(newPermissionTemplateDto() .setUuid(uuid) .setName("Default template for Projects") .setDescription("Template for new projects") .setKeyPattern(null) .setCreatedAt(new Date(1_000_000_000_000L)) .setUpdatedAt(new Date(1_000_000_000_000L))); } private PermissionTemplateDto insertPortfoliosTemplate() { return insertTemplate(newPermissionTemplateDto() .setUuid(UUID_EXAMPLE_02) .setName("Default template for Portfolios") .setDescription("Template for new portfolios") .setKeyPattern(".*sonar.views.*") .setCreatedAt(new Date(1_000_000_000_000L)) .setUpdatedAt(new Date(1_100_000_000_000L))); } private PermissionTemplateDto insertApplicationsTemplate() { return insertTemplate(newPermissionTemplateDto() .setUuid(UUID_EXAMPLE_10) .setName("Default template for Applications") .setDescription("Template for new applications") .setKeyPattern(".*sonar.views.*") .setCreatedAt(new Date(1_000_000_000_000L)) .setUpdatedAt(new Date(1_100_000_000_000L))); } private PermissionTemplateDto insertTemplate(PermissionTemplateDto template) { PermissionTemplateDto insert = dbClient.permissionTemplateDao().insert(db.getSession(), template); db.getSession().commit(); return insert; } private void addGroupToTemplate(String templateUuid, @Nullable String groupUuid, String permission, String templateName, String groupName) { dbClient.permissionTemplateDao().insertGroupPermission(db.getSession(), templateUuid, groupUuid, permission, templateName, groupName); db.getSession().commit(); } private void addUserToTemplate(String templateUuid, String userId, String permission, String templateName, String userLogin) { dbClient.permissionTemplateDao().insertUserPermission(db.getSession(), templateUuid, userId, permission, templateName, userLogin); db.getSession().commit(); } private void addPermissionTemplateWithProjectCreator(String templateUuid, String permission, String templateName) { dbClient.permissionTemplateCharacteristicDao().insert(dbSession, new PermissionTemplateCharacteristicDto() .setUuid(Uuids.createFast()) .setWithProjectCreator(true) .setTemplateUuid(templateUuid) .setPermission(permission) .setCreatedAt(1_000_000_000L) .setUpdatedAt(2_000_000_000L), templateName); db.commit(); } private TestRequest newRequest(WsActionTester underTest) { return underTest.newRequest().setMethod("POST"); } }
17,578
44.898172
237
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.db.DbSession; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.l18n.I18nRule; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.property.InternalProperties; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class SetDefaultTemplateActionIT extends BasePermissionWsIT<SetDefaultTemplateAction> { private I18nRule i18n = new I18nRule(); @Override protected SetDefaultTemplateAction buildWsAction() { return new SetDefaultTemplateAction(db.getDbClient(), newPermissionWsSupport(), newRootResourceTypes(), userSession, i18n); } @Test public void update_project_default_template() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate(); db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); newRequest(template.getUuid(), Qualifiers.PROJECT); assertDefaultTemplates(template.getUuid(), applicationDefaultTemplate.getUuid(), portfolioDefaultTemplate.getUuid()); } @Test public void update_project_default_template_without_qualifier_param() { db.permissionTemplates().setDefaultTemplates("any-project-template-uuid", "any-view-template-uuid", null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); // default value is project qualifier's value newRequest(template.getUuid(), null); assertDefaultTemplates(template.getUuid(), "any-view-template-uuid", null); } @Test public void update_project_default_template_by_template_name() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate(); PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate(); db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); newRequest() .setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase()) .execute(); db.getSession().commit(); assertDefaultTemplates(template.getUuid(), applicationDefaultTemplate.getUuid(), portfolioDefaultTemplate.getUuid()); } @Test public void update_view_default_template() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); newRequest(template.getUuid(), VIEW); assertDefaultTemplates(projectDefaultTemplate.getUuid(), null, template.getUuid()); } @Test public void update_app_default_template() { PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate(); db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null); PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); newRequest(template.getUuid(), APP); assertDefaultTemplates(projectDefaultTemplate.getUuid(), template.getUuid(), null); } @Test public void fail_if_anonymous() { PermissionTemplateDto template = insertTemplate(); userSession.anonymous(); assertThatThrownBy(() -> { newRequest(template.getUuid(), PROJECT); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_not_admin() { PermissionTemplateDto template = insertTemplate(); userSession.logIn(); assertThatThrownBy(() -> { newRequest(template.getUuid(), null); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_template_not_provided() { assertThatThrownBy(() -> { newRequest(null, PROJECT); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_does_not_exist() { assertThatThrownBy(() -> { newRequest("unknown-template-uuid", PROJECT); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_qualifier_is_not_root() { PermissionTemplateDto template = insertTemplate(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest(template.getUuid(), Qualifiers.FILE); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of parameter 'qualifier' (FIL) must be one of: [APP, TRK, VW]"); } private void newRequest(@Nullable String templateUuid, @Nullable String qualifier) { TestRequest request = newRequest(); if (templateUuid != null) { request.setParam(PARAM_TEMPLATE_ID, templateUuid); } if (qualifier != null) { request.setParam(PARAM_QUALIFIER, qualifier); } request.execute(); } private PermissionTemplateDto insertTemplate() { return db.permissionTemplates().insertTemplate(); } private void assertDefaultTemplates(@Nullable String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfolioDefaultTemplateUuid) { DbSession dbSession = db.getSession(); if (projectDefaultTemplateUuid != null) { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).contains(projectDefaultTemplateUuid); } else { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).isEmpty(); } if (portfolioDefaultTemplateUuid != null) { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).contains(portfolioDefaultTemplateUuid); } else { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).isEmpty(); } if (applicationDefaultTemplateUuid != null) { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).contains(applicationDefaultTemplateUuid); } else { assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).isEmpty(); } } }
8,401
39.985366
180
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/TemplateGroupsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.permission.template.PermissionTemplateGroupDto; import org.sonar.db.user.GroupDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonarqube.ws.Permissions.WsGroupsResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateGroupDto; import static org.sonar.db.user.GroupTesting.newGroupDto; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class TemplateGroupsActionIT extends BasePermissionWsIT<TemplateGroupsAction> { private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); private final RequestValidator requestValidator = new RequestValidator(permissionService); @Override protected TemplateGroupsAction buildWsAction() { return new TemplateGroupsAction(db.getDbClient(), userSession, newPermissionWsSupport(), wsParameters, requestValidator); } @Test public void define_template_groups() { WebService.Action action = wsTester.getDef(); assertThat(action).isNotNull(); assertThat(action.key()).isEqualTo("template_groups"); assertThat(action.isPost()).isFalse(); assertThat(action.isInternal()).isTrue(); assertThat(action.since()).isEqualTo("5.2"); } @Test public void template_groups_of_json_example() { GroupDto adminGroup = insertGroup("sonar-administrators", "System administrators"); GroupDto userGroup = insertGroup("sonar-users", "Every authenticated user automatically belongs to this group"); PermissionTemplateDto template = addTemplate(); addGroupToTemplate(newPermissionTemplateGroup(ISSUE_ADMIN, template.getUuid(), adminGroup.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ISSUE_ADMIN, template.getUuid(), userGroup.getUuid()), template.getName()); // Anyone group addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), null), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ISSUE_ADMIN, template.getUuid(), null), template.getName()); loginAsAdmin(); String response = newRequest() .setParam(PARAM_PERMISSION, ISSUE_ADMIN) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .execute() .getInput(); assertJson(response) .ignoreFields("id") .withStrictArrayOrder() .isSimilarTo(getClass().getResource("template_groups-example.json")); } @Test public void return_all_permissions_of_matching_groups() { PermissionTemplateDto template = addTemplate(); GroupDto group1 = db.users().insertGroup("group-1-name"); addGroupToTemplate(newPermissionTemplateGroup(CODEVIEWER, template.getUuid(), group1.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, template.getUuid(), group1.getUuid()), template.getName()); GroupDto group2 = db.users().insertGroup("group-2-name"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group2.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, template.getUuid(), group2.getUuid()), template.getName()); GroupDto group3 = db.users().insertGroup("group-3-name"); // Anyone addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), null), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ISSUE_ADMIN, template.getUuid(), null), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); GroupDto group4 = db.users().insertGroup("group-4-name"); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, anotherTemplate.getUuid(), group3.getUuid()), anotherTemplate.getName()); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, anotherTemplate.getUuid(), group4.getUuid()), anotherTemplate.getName()); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("Anyone", "group-1-name", "group-2-name", "group-3-name", "group-4-name"); assertThat(response.getGroups(0).getPermissionsList()).containsOnly("user", "issueadmin"); assertThat(response.getGroups(1).getPermissionsList()).containsOnly("codeviewer", "admin"); assertThat(response.getGroups(2).getPermissionsList()).containsOnly("user", "admin"); assertThat(response.getGroups(3).getPermissionsList()).isEmpty(); } @Test public void search_by_permission() { PermissionTemplateDto template = addTemplate(); GroupDto group1 = db.users().insertGroup("group-1-name"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group1.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(CODEVIEWER, template.getUuid(), group1.getUuid()), template.getName()); GroupDto group2 = db.users().insertGroup("group-2-name"); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, template.getUuid(), group2.getUuid()), template.getName()); GroupDto group3 = db.users().insertGroup("group-3-name"); // Anyone addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), null), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, anotherTemplate.getUuid(), group3.getUuid()), anotherTemplate.getName()); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("Anyone", "group-1-name"); assertThat(response.getGroups(0).getPermissionsList()).containsOnly("user"); assertThat(response.getGroups(1).getPermissionsList()).containsOnly("user", "codeviewer"); } @Test public void search_by_template_name() { GroupDto group1 = db.users().insertGroup("group-1-name"); GroupDto group2 = db.users().insertGroup("group-2-name"); GroupDto group3 = db.users().insertGroup("group-3-name"); PermissionTemplateDto template = addTemplate(); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group1.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(ADMIN, template.getUuid(), group2.getUuid()), template.getName()); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), null), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addGroupToTemplate(newPermissionTemplateGroup(USER, anotherTemplate.getUuid(), group1.getUuid()), anotherTemplate.getName()); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_NAME, template.getName()) .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("Anyone", "group-1-name", "group-2-name", "group-3-name"); } @Test public void search_with_pagination() { PermissionTemplateDto template = addTemplate(); GroupDto group1 = db.users().insertGroup("group-1-name"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group1.getUuid()), template.getName()); GroupDto group2 = db.users().insertGroup("group-2-name"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group2.getUuid()), template.getName()); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .setParam(PAGE, "2") .setParam(PAGE_SIZE, "1") .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("group-2-name"); } @Test public void search_with_text_query() { PermissionTemplateDto template = addTemplate(); GroupDto group1 = db.users().insertGroup("group-1-name"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group1.getUuid()), template.getName()); GroupDto group2 = db.users().insertGroup("group-2-name"); GroupDto group3 = db.users().insertGroup("group-3"); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_NAME, template.getName()) .setParam(TEXT_QUERY, "-nam") .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("group-1-name", "group-2-name"); } @Test public void search_with_text_query_return_all_groups_even_when_no_permission_set() { PermissionTemplateDto template = addTemplate(); db.users().insertGroup("group-1-name"); db.users().insertGroup("group-2-name"); db.users().insertGroup("group-3-name"); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .setParam(TEXT_QUERY, "-name") .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("group-1-name", "group-2-name", "group-3-name"); assertThat(response.getGroups(0).getPermissionsList()).isEmpty(); assertThat(response.getGroups(1).getPermissionsList()).isEmpty(); assertThat(response.getGroups(2).getPermissionsList()).isEmpty(); } @Test public void search_with_text_query_return_anyone_group_even_when_no_permission_set() { PermissionTemplateDto template = addTemplate(); GroupDto group = db.users().insertGroup("group"); addGroupToTemplate(newPermissionTemplateGroup(USER, template.getUuid(), group.getUuid()), template.getName()); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .setParam(TEXT_QUERY, "nyo") .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()).extracting("name").containsExactly("Anyone"); assertThat(response.getGroups(0).getPermissionsList()).isEmpty(); } @Test public void search_ignores_other_template_and_is_ordered_by_groups_with_permission_then_by_name_when_many_groups() { PermissionTemplateDto template = addTemplate(); PermissionTemplateDto otherTemplate = db.permissionTemplates().insertTemplate(); IntStream.rangeClosed(1, DEFAULT_PAGE_SIZE + 1).forEach(i -> { GroupDto group = db.users().insertGroup("Group-" + i); db.permissionTemplates().addGroupToTemplate(otherTemplate, group, UserRole.USER); }); String lastGroupName = "Group-" + (DEFAULT_PAGE_SIZE + 1); db.permissionTemplates().addGroupToTemplate(template, db.users().selectGroup(lastGroupName).get(), UserRole.USER); loginAsAdmin(); WsGroupsResponse response = newRequest() .setParam(PARAM_TEMPLATE_ID, template.getUuid()) .executeProtobuf(WsGroupsResponse.class); assertThat(response.getGroupsList()) .extracting("name") .hasSize(DEFAULT_PAGE_SIZE) .startsWith("Anyone", lastGroupName, "Group-1"); } @Test public void fail_if_not_logged_in() { PermissionTemplateDto template1 = addTemplate(); userSession.anonymous(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { PermissionTemplateDto template1 = addTemplate(); userSession.logIn(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .execute(); }) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_template_uuid_and_name_provided() { PermissionTemplateDto template1 = addTemplate(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .setParam(PARAM_TEMPLATE_NAME, template1.getName()) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_uuid_nor_name_provided() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, USER) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_is_not_found() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, USER) .setParam(PARAM_TEMPLATE_ID, "unknown-uuid") .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_not_a_project_permission() { loginAsAdmin(); PermissionTemplateDto template1 = addTemplate(); assertThatThrownBy(() -> { newRequest() .setParam(PARAM_PERMISSION, ADMINISTER_QUALITY_GATES.getKey()) .setParam(PARAM_TEMPLATE_ID, template1.getUuid()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } private GroupDto insertGroup(String name, String description) { return db.users().insertGroup(newGroupDto().setName(name).setDescription(description)); } private void addGroupToTemplate(PermissionTemplateGroupDto permissionTemplateGroup, String templateName) { db.getDbClient().permissionTemplateDao().insertGroupPermission(db.getSession(), permissionTemplateGroup, templateName); db.commit(); } private static PermissionTemplateGroupDto newPermissionTemplateGroup(String permission, String templateUuid, @Nullable String groupUuid) { return newPermissionTemplateGroupDto() .setPermission(permission) .setTemplateUuid(templateUuid) .setGroupUuid(groupUuid); } }
16,784
42.1491
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/TemplateUsersActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.permission.template.PermissionTemplateUserDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.issue.AvatarResolverImpl; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.RequestValidator; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.permission.ws.WsParameters; import org.sonar.server.ws.TestRequest; import org.sonarqube.ws.Permissions; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.CODEVIEWER; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.db.permission.PermissionQuery.DEFAULT_PAGE_SIZE; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateUserDto; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME; public class TemplateUsersActionIT extends BasePermissionWsIT<TemplateUsersAction> { private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final WsParameters wsParameters = new WsParameters(permissionService); private final RequestValidator requestValidator = new RequestValidator(permissionService); @Override protected TemplateUsersAction buildWsAction() { return new TemplateUsersAction(db.getDbClient(), userSession, newPermissionWsSupport(), new AvatarResolverImpl(), wsParameters, requestValidator); } @Test public void define_template_users() { WebService.Action action = wsTester.getDef(); assertThat(action).isNotNull(); assertThat(action.key()).isEqualTo("template_users"); assertThat(action.isPost()).isFalse(); assertThat(action.isInternal()).isTrue(); assertThat(action.since()).isEqualTo("5.2"); WebService.Param permissionParam = action.param(PARAM_PERMISSION); assertThat(permissionParam).isNotNull(); assertThat(permissionParam.isRequired()).isFalse(); } @Test public void search_for_users_with_response_example() { UserDto user1 = insertUser(newUserDto().setLogin("admin").setName("Administrator").setEmail("admin@admin.com")); UserDto user2 = insertUser(newUserDto().setLogin("george.orwell").setName("George Orwell").setEmail("george.orwell@1984.net")); PermissionTemplateDto template1 = addTemplate(); addUserToTemplate(newPermissionTemplateUser(CODEVIEWER, template1, user1), template1.getName()); addUserToTemplate(newPermissionTemplateUser(CODEVIEWER, template1, user2), template1.getName()); addUserToTemplate(newPermissionTemplateUser(ADMIN, template1, user2), template1.getName()); loginAsAdmin(); String result = newRequest(null, template1.getUuid()).execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("template_users-example.json")); } @Test public void search_for_users_by_template_name() { loginAsAdmin(); UserDto user1 = insertUser(newUserDto().setLogin("login-1").setName("name-1").setEmail("email-1")); UserDto user2 = insertUser(newUserDto().setLogin("login-2").setName("name-2").setEmail("email-2")); UserDto user3 = insertUser(newUserDto().setLogin("login-3").setName("name-3").setEmail("email-3")); PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user3), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate, user1), anotherTemplate.getName()); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2", "login-3"); assertThat(response.getUsers(0).getPermissionsList()).containsOnly("issueadmin", "user"); assertThat(response.getUsers(1).getPermissionsList()).containsOnly("user"); assertThat(response.getUsers(2).getPermissionsList()).containsOnly("issueadmin"); } @Test public void search_using_text_query() { loginAsAdmin(); UserDto user1 = insertUser(newUserDto().setLogin("login-1").setName("name-1").setEmail("email-1")); UserDto user2 = insertUser(newUserDto().setLogin("login-2").setName("name-2").setEmail("email-2")); UserDto user3 = insertUser(newUserDto().setLogin("login-3").setName("name-3").setEmail("email-3")); PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user3), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate, user1), anotherTemplate.getName()); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .setParam(WebService.Param.TEXT_QUERY, "ame-1") .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).extracting("login").containsOnly("login-1"); } @Test public void search_using_text_query_with_email() { loginAsAdmin(); UserDto user1 = insertUser(newUserDto().setLogin("orange").setName("name-1").setEmail("email-1")); UserDto user2 = insertUser(newUserDto().setLogin("crANBerry").setName("name-2").setEmail("email-2")); UserDto user3 = insertUser(newUserDto().setLogin("apple").setName("name-3").setEmail("email-3")); String templateName = addUsersToSomeTemplate(user1, user2, user3); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, templateName) .setParam(WebService.Param.TEXT_QUERY, "ran") .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).hasSize(2); assertThat(response.getUsersList()).extracting("login").containsExactlyInAnyOrder("orange", "crANBerry"); } @Test public void search_using_text_query_with_login() { loginAsAdmin(); UserDto user1 = insertUser(newUserDto().setLogin("login-1").setName("name-1").setEmail("xYZ@1984.com")); UserDto user2 = insertUser(newUserDto().setLogin("login-2").setName("name-2").setEmail("xyz2@1984.com")); UserDto user3 = insertUser(newUserDto().setLogin("login-3").setName("name-3").setEmail("hello@1984.com")); String templateName = addUsersToSomeTemplate(user1, user2, user3); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, templateName) .setParam(WebService.Param.TEXT_QUERY, "xyz") .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).hasSize(2); assertThat(response.getUsersList()).extracting("email").containsExactlyInAnyOrder("xYZ@1984.com", "xyz2@1984.com"); } private String addUsersToSomeTemplate(UserDto user1, UserDto user2, UserDto user3) { PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user3), template.getName()); return template.getName(); } @Test public void search_using_permission() { UserDto user1 = insertUser(newUserDto().setLogin("login-1").setName("name-1").setEmail("email-1")); UserDto user2 = insertUser(newUserDto().setLogin("login-2").setName("name-2").setEmail("email-2")); UserDto user3 = insertUser(newUserDto().setLogin("login-3").setName("name-3").setEmail("email-3")); PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user3), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate, user1), anotherTemplate.getName()); loginAsAdmin(); Permissions.UsersWsResponse response = newRequest(USER, template.getUuid()) .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2"); assertThat(response.getUsers(0).getPermissionsList()).containsOnly("issueadmin", "user"); assertThat(response.getUsers(1).getPermissionsList()).containsOnly("user"); } @Test public void search_with_pagination() { UserDto user1 = insertUser(newUserDto().setLogin("login-1").setName("name-1").setEmail("email-1")); UserDto user2 = insertUser(newUserDto().setLogin("login-2").setName("name-2").setEmail("email-2")); UserDto user3 = insertUser(newUserDto().setLogin("login-3").setName("name-3").setEmail("email-3")); PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user3), template.getName()); PermissionTemplateDto anotherTemplate = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, anotherTemplate, user1), anotherTemplate.getName()); loginAsAdmin(); Permissions.UsersWsResponse response = newRequest(USER, null) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .setParam(WebService.Param.SELECTED, "all") .setParam(WebService.Param.PAGE, "2") .setParam(WebService.Param.PAGE_SIZE, "1") .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).extracting("login").containsOnly("login-2"); } @Test public void users_are_sorted_by_name() { UserDto user1 = insertUser(newUserDto().setLogin("login-2").setName("name-2")); UserDto user2 = insertUser(newUserDto().setLogin("login-3").setName("name-3")); UserDto user3 = insertUser(newUserDto().setLogin("login-1").setName("name-1")); PermissionTemplateDto template = addTemplate(); addUserToTemplate(newPermissionTemplateUser(USER, template, user1), template.getName()); addUserToTemplate(newPermissionTemplateUser(USER, template, user2), template.getName()); addUserToTemplate(newPermissionTemplateUser(ISSUE_ADMIN, template, user3), template.getName()); loginAsAdmin(); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()).extracting("login").containsExactly("login-1", "login-2", "login-3"); } @Test public void search_ignores_other_template_and_is_ordered_by_users_with_permission_when_many_users() { PermissionTemplateDto template = addTemplate(); // Add another template having some users with permission to make sure it's correctly ignored PermissionTemplateDto otherTemplate = db.permissionTemplates().insertTemplate(); IntStream.rangeClosed(1, DEFAULT_PAGE_SIZE + 1).forEach(i -> { UserDto user = db.users().insertUser("User-" + i); db.permissionTemplates().addUserToTemplate(otherTemplate, user, UserRole.USER); }); String lastLogin = "User-" + (DEFAULT_PAGE_SIZE + 1); db.permissionTemplates().addUserToTemplate(template, db.users().selectUserByLogin(lastLogin).get(), UserRole.USER); loginAsAdmin(); Permissions.UsersWsResponse response = newRequest(null, null) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .executeProtobuf(Permissions.UsersWsResponse.class); assertThat(response.getUsersList()) .extracting("login") .hasSize(DEFAULT_PAGE_SIZE) .startsWith(lastLogin); } @Test public void fail_if_not_a_project_permission() { PermissionTemplateDto template = addTemplate(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest(GlobalPermission.PROVISION_PROJECTS.getKey(), template.getUuid()) .execute(); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_no_template_param() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(null, null) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_template_does_not_exist() { loginAsAdmin(); assertThatThrownBy(() -> { newRequest(null, "unknown-template-uuid") .execute(); }) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_template_uuid_and_name_provided() { PermissionTemplateDto template = addTemplate(); loginAsAdmin(); assertThatThrownBy(() -> { newRequest(null, template.getUuid()) .setParam(PARAM_TEMPLATE_NAME, template.getName()) .execute(); }) .isInstanceOf(BadRequestException.class); } @Test public void fail_if_not_logged_in() { PermissionTemplateDto template = addTemplate(); userSession.anonymous(); assertThatThrownBy(() -> { newRequest(null, template.getUuid()).execute(); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_insufficient_privileges() { PermissionTemplateDto template = addTemplate(); userSession.logIn().addPermission(SCAN); assertThatThrownBy(() -> { newRequest(null, template.getUuid()).execute(); }) .isInstanceOf(ForbiddenException.class); } private UserDto insertUser(UserDto userDto) { db.users().insertUser(userDto); return userDto; } private void addUserToTemplate(PermissionTemplateUserDto dto, String templateName) { db.getDbClient().permissionTemplateDao().insertUserPermission(db.getSession(), dto.getTemplateUuid(), dto.getUserUuid(), dto.getPermission(), templateName, dto.getUserLogin()); db.commit(); } private static PermissionTemplateUserDto newPermissionTemplateUser(String permission, PermissionTemplateDto template, UserDto user) { return newPermissionTemplateUserDto() .setPermission(permission) .setTemplateUuid(template.getUuid()) .setUserUuid(user.getUuid()); } private TestRequest newRequest(@Nullable String permission, @Nullable String templateUuid) { TestRequest request = newRequest(); if (permission != null) { request.setParam(PARAM_PERMISSION, permission); } if (templateUuid != null) { request.setParam(PARAM_TEMPLATE_ID, templateUuid); } return request; } }
17,742
44.378517
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/permission/ws/template/UpdateTemplateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.ws.template; import java.util.Date; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.ws.BasePermissionWsIT; import org.sonar.server.ws.TestRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.SCAN; import static org.sonar.db.permission.template.PermissionTemplateTesting.newPermissionTemplateDto; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_DESCRIPTION; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_ID; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PROJECT_KEY_PATTERN; public class UpdateTemplateActionIT extends BasePermissionWsIT<UpdateTemplateAction> { private final System2 system = spy(System2.INSTANCE); private PermissionTemplateDto template; @Override protected UpdateTemplateAction buildWsAction() { return new UpdateTemplateAction(db.getDbClient(), userSession, system, newPermissionWsSupport()); } @Before public void setUp() { when(system.now()).thenReturn(1_440_512_328_743L); template = db.getDbClient().permissionTemplateDao().insert(db.getSession(), newPermissionTemplateDto() .setName("Permission Template Name") .setDescription("Permission Template Description") .setKeyPattern(".*\\.pattern\\..*") .setCreatedAt(new Date(1_000_000_000_000L)) .setUpdatedAt(new Date(1_000_000_000_000L))); db.commit(); } @Test public void update_all_permission_template_fields() { loginAsAdmin(); String result = call(template.getUuid(), "Finance", "Permissions for financially related projects", ".*\\.finance\\..*"); assertJson(result) .ignoreFields("id") .isSimilarTo(getClass().getResource("update_template-example.json")); PermissionTemplateDto finance = selectPermissionTemplate("Finance"); assertThat(finance.getName()).isEqualTo("Finance"); assertThat(finance.getDescription()).isEqualTo("Permissions for financially related projects"); assertThat(finance.getKeyPattern()).isEqualTo(".*\\.finance\\..*"); assertThat(finance.getUuid()).isEqualTo(template.getUuid()); assertThat(finance.getCreatedAt()).isEqualTo(template.getCreatedAt()); assertThat(finance.getUpdatedAt().getTime()).isEqualTo(1440512328743L); } @Test public void update_with_the_same_values() { loginAsAdmin(); call(template.getUuid(), template.getName(), template.getDescription(), template.getKeyPattern()); PermissionTemplateDto reloaded = db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), template.getUuid()); assertThat(reloaded.getName()).isEqualTo(template.getName()); assertThat(reloaded.getDescription()).isEqualTo(template.getDescription()); assertThat(reloaded.getKeyPattern()).isEqualTo(template.getKeyPattern()); } @Test public void update_with_null_values() { template = db.getDbClient().permissionTemplateDao().insert(db.getSession(), newPermissionTemplateDto() .setName("Test") .setDescription(null) .setKeyPattern(null) .setCreatedAt(new Date(1_000_000_000_000L)) .setUpdatedAt(new Date(1_000_000_000_000L))); db.commit(); loginAsAdmin(); call(template.getUuid(), template.getName(), null, null); PermissionTemplateDto reloaded = db.getDbClient().permissionTemplateDao().selectByUuid(db.getSession(), template.getUuid()); assertThat(reloaded.getName()).isEqualTo(template.getName()); assertThat(reloaded.getDescription()).isNull(); assertThat(reloaded.getKeyPattern()).isNull(); } @Test public void update_name_only() { loginAsAdmin(); call(template.getUuid(), "Finance", null, null); PermissionTemplateDto finance = selectPermissionTemplate("Finance"); assertThat(finance.getName()).isEqualTo("Finance"); assertThat(finance.getDescription()).isEqualTo(template.getDescription()); assertThat(finance.getKeyPattern()).isEqualTo(template.getKeyPattern()); } @Test public void fail_if_key_is_not_found() { loginAsAdmin(); assertThatThrownBy(() -> { call("unknown-key", null, null, null); }) .isInstanceOf(NotFoundException.class) .hasMessage("Permission template with id 'unknown-key' is not found"); } @Test public void fail_if_name_already_exists_in_another_template() { loginAsAdmin(); PermissionTemplateDto anotherTemplate = addTemplate(); assertThatThrownBy(() -> { call(this.template.getUuid(), anotherTemplate.getName(), null, null); }) .isInstanceOf(BadRequestException.class) .hasMessage("A template with the name '" + anotherTemplate.getName() + "' already exists (case insensitive)."); } @Test public void fail_if_key_is_not_provided() { loginAsAdmin(); assertThatThrownBy(() -> { call(null, "Finance", null, null); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_name_empty() { loginAsAdmin(); assertThatThrownBy(() -> { call(template.getUuid(), "", null, null); }) .isInstanceOf(BadRequestException.class) .hasMessage("The template name must not be blank"); } @Test public void fail_if_name_has_just_whitespaces() { loginAsAdmin(); assertThatThrownBy(() -> { call(template.getUuid(), " \r\n", null, null); }) .isInstanceOf(BadRequestException.class) .hasMessage("The template name must not be blank"); } @Test public void fail_if_regexp_if_not_valid() { loginAsAdmin(); assertThatThrownBy(() -> { call(template.getUuid(), "Finance", null, "[azerty"); }) .isInstanceOf(BadRequestException.class) .hasMessage("The 'projectKeyPattern' parameter must be a valid Java regular expression. '[azerty' was passed"); } @Test public void fail_if_name_already_exists_in_database_case_insensitive() { loginAsAdmin(); PermissionTemplateDto anotherTemplate = addTemplate(); String nameCaseInsensitive = anotherTemplate.getName().toUpperCase(); assertThatThrownBy(() -> { call(this.template.getUuid(), nameCaseInsensitive, null, null); }) .isInstanceOf(BadRequestException.class) .hasMessage("A template with the name '" + nameCaseInsensitive + "' already exists (case insensitive)."); } @Test public void fail_if_not_logged_in() { assertThatThrownBy(() -> { userSession.anonymous(); call(template.getUuid(), "Finance", null, null); }) .isInstanceOf(UnauthorizedException.class); } @Test public void fail_if_not_admin() { userSession.logIn().addPermission(SCAN); assertThatThrownBy(() -> { call(template.getUuid(), "Finance", null, null); }) .isInstanceOf(ForbiddenException.class); } private String call(@Nullable String key, @Nullable String name, @Nullable String description, @Nullable String projectPattern) { TestRequest request = newRequest(); if (key != null) { request.setParam(PARAM_ID, key); } if (name != null) { request.setParam(PARAM_NAME, name); } if (description != null) { request.setParam(PARAM_DESCRIPTION, description); } if (projectPattern != null) { request.setParam(PARAM_PROJECT_KEY_PATTERN, projectPattern); } return request.execute().getInput(); } }
8,922
34.835341
131
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/platform/ws/LogsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import java.io.File; import java.io.IOException; import java.util.Set; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.log.ServerLogging; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.MediaTypes; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LogsActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public TemporaryFolder temp = new TemporaryFolder(); private ServerLogging serverLogging = mock(ServerLogging.class); private LogsAction underTest = new LogsAction(userSession, serverLogging); private WsActionTester actionTester = new WsActionTester(underTest); @Test public void values_of_process_parameter_are_names_of_processes() { Set<String> values = actionTester.getDef().param("process").possibleValues(); // values are lower-case and alphabetically ordered assertThat(values).containsExactly("access", "app", "ce", "es", "web"); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() { assertThatThrownBy(() -> actionTester.newRequest().execute()) .isInstanceOf(ForbiddenException.class); } @Test public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() { userSession.logIn(); assertThatThrownBy(() -> actionTester.newRequest().execute()) .isInstanceOf(ForbiddenException.class); } @Test public void get_app_logs_by_default() throws IOException { logInAsSystemAdministrator(); createAllLogsFiles(); TestResponse response = actionTester.newRequest().execute(); assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT); assertThat(response.getInput()).isEqualTo("{app}"); } @Test public void return_404_not_found_if_file_does_not_exist() throws IOException { logInAsSystemAdministrator(); createLogsDir(); TestResponse response = actionTester.newRequest().execute(); assertThat(response.getStatus()).isEqualTo(404); } @Test public void download_logs() throws IOException { logInAsSystemAdministrator(); createAllLogsFiles(); asList("ce", "es", "web", "access").forEach(process -> { TestResponse response = actionTester.newRequest() .setParam("process", process) .execute(); assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT); assertThat(response.getInput()).isEqualTo("{" + process + "}"); }); } @Test public void do_not_return_rotated_files() throws IOException { logInAsSystemAdministrator(); File dir = createLogsDir(); FileUtils.write(new File(dir, "sonar.1.log"), "{old}"); FileUtils.write(new File(dir, "sonar.log"), "{recent}"); TestResponse response = actionTester.newRequest() .setParam("process", "app") .execute(); assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT); assertThat(response.getInput()).isEqualTo("{recent}"); } @Test public void create_latest_created_file() throws IOException { logInAsSystemAdministrator(); File dir = createLogsDir(); FileUtils.write(new File(dir, "sonar.20210101.log"), "{old}"); FileUtils.write(new File(dir, "sonar.20210201.log"), "{recent}"); TestResponse response = actionTester.newRequest() .setParam("process", "app") .execute(); assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT); assertThat(response.getInput()).isEqualTo("{recent}"); } private File createAllLogsFiles() throws IOException { File dir = createLogsDir(); FileUtils.write(new File(dir, "access.log"), "{access}"); FileUtils.write(new File(dir, "sonar.log"), "{app}"); FileUtils.write(new File(dir, "ce.log"), "{ce}"); FileUtils.write(new File(dir, "es.log"), "{es}"); FileUtils.write(new File(dir, "web.log"), "{web}"); return dir; } private File createLogsDir() throws IOException { File dir = temp.newFolder(); when(serverLogging.getLogsDir()).thenReturn(dir); return dir; } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } }
5,437
32.9875
93
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/platform/ws/SafeModeMonitoringMetricActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform.ws; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.user.BearerPasscode; import org.sonar.server.user.SystemPasscode; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.server.tester.UserSessionRule.standalone; public class SafeModeMonitoringMetricActionIT { @Rule public UserSessionRule userSession = standalone(); @Rule public DbTester db = DbTester.create(); private final BearerPasscode bearerPasscode = mock(BearerPasscode.class); private final SystemPasscode systemPasscode = mock(SystemPasscode.class); private final SafeModeMonitoringMetricAction safeModeMonitoringMetricAction = new SafeModeMonitoringMetricAction(systemPasscode, bearerPasscode); private final WsActionTester ws = new WsActionTester(safeModeMonitoringMetricAction); @Test public void no_authentication_throw_insufficient_privileges_error() { TestRequest request = ws.newRequest(); Assertions.assertThatThrownBy(request::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } @Test public void authenticated_non_global_admin_is_forbidden() { userSession.logIn(); TestRequest testRequest = ws.newRequest(); Assertions.assertThatThrownBy(testRequest::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } @Test public void authentication_passcode_is_allowed() { when(systemPasscode.isValid(any())).thenReturn(true); TestResponse response = ws.newRequest().execute(); String content = response.getInput(); assertThat(content) .contains("# HELP sonarqube_health_web_status Tells whether Web process is up or down. 1 for up, 0 for down") .contains("# TYPE sonarqube_health_web_status gauge") .contains("sonarqube_health_web_status 1.0"); } @Test public void authentication_bearer_passcode_is_allowed() { when(bearerPasscode.isValid(any())).thenReturn(true); TestResponse response = ws.newRequest().execute(); String content = response.getInput(); assertThat(content) .contains("# HELP sonarqube_health_web_status Tells whether Web process is up or down. 1 for up, 0 for down") .contains("# TYPE sonarqube_health_web_status gauge") .contains("sonarqube_health_web_status 1.0"); } @Test public void authenticated_global_admin_is_not_allowed_in_safe_mode() { userSession.logIn().setSystemAdministrator(); TestRequest testRequest = ws.newRequest(); Assertions.assertThatThrownBy(testRequest::execute) .hasMessage("Insufficient privileges") .isInstanceOf(ForbiddenException.class); } }
3,978
36.186916
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/plugins/ws/InstalledActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.plugins.ws; import com.hazelcast.internal.json.Json; import com.hazelcast.internal.json.JsonArray; import com.hazelcast.internal.json.JsonObject; import com.hazelcast.internal.json.JsonValue; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Optional; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Action; import org.sonar.api.utils.System2; import org.sonar.core.platform.PluginInfo; import org.sonar.db.DbTester; import org.sonar.db.plugin.PluginDto.Type; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPlugin; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.server.plugins.UpdateCenterMatrixFactory; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; @RunWith(DataProviderRunner.class) public class InstalledActionIT { private static final String JSON_EMPTY_PLUGIN_LIST = "{" + " \"plugins\":" + "[]" + "}"; @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn(); private UpdateCenterMatrixFactory updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class, RETURNS_DEEP_STUBS); private ServerPluginRepository serverPluginRepository = mock(ServerPluginRepository.class); private InstalledAction underTest = new InstalledAction(serverPluginRepository, userSession, updateCenterMatrixFactory, db.getDbClient()); private WsActionTester tester = new WsActionTester(underTest); @DataProvider public static Object[][] editionBundledLicenseValues() { return new Object[][] { {"sonarsource"}, {"SonarSource"}, {"SonaRSOUrce"}, {"SONARSOURCE"}, {"commercial"}, {"Commercial"}, {"COMMERCIAL"}, {"COmmERCiaL"}, }; } @Test public void action_installed_is_defined() { Action action = tester.getDef(); assertThat(action.isPost()).isFalse(); assertThat(action.description()).isNotEmpty(); assertThat(action.responseExample()).isNotNull(); } @Test public void empty_array_is_returned_when_there_is_not_plugin_installed() { String response = tester.newRequest().execute().getInput(); assertJson(response).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); } @Test public void empty_array_when_update_center_is_unavailable() { when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.empty()); String response = tester.newRequest().execute().getInput(); assertJson(response).withStrictArrayOrder().isSimilarTo(JSON_EMPTY_PLUGIN_LIST); } @Test public void filter_by_plugin_type() throws IOException { when(serverPluginRepository.getPlugins()).thenReturn( Arrays.asList( newInstalledPlugin(new PluginInfo("foo-external-1") .setName("foo-external-1"), PluginType.EXTERNAL), newInstalledPlugin(new PluginInfo("foo-bundled-1") .setName("foo-bundled-1"), PluginType.BUNDLED), newInstalledPlugin(new PluginInfo("foo-external-2") .setName("foo-external-2"), PluginType.EXTERNAL))); db.pluginDbTester().insertPlugin( p -> p.setKee("foo-external-1"), p -> p.setType(Type.EXTERNAL), p -> p.setUpdatedAt(100L)); db.pluginDbTester().insertPlugin( p -> p.setKee("foo-bundled-1"), p -> p.setType(Type.BUNDLED), p -> p.setUpdatedAt(101L)); db.pluginDbTester().insertPlugin( p -> p.setKee("foo-external-2"), p -> p.setType(Type.EXTERNAL), p -> p.setUpdatedAt(102L)); // no type param String response = tester.newRequest().execute().getInput(); JsonArray jsonArray = Json.parse(response).asObject().get("plugins").asArray(); assertThat(jsonArray).hasSize(3); assertThat(jsonArray).extracting(JsonValue::asObject) .extracting(members -> members.get("key").asString()) .containsExactlyInAnyOrder("foo-external-1", "foo-bundled-1", "foo-external-2"); // type param == BUNDLED response = tester.newRequest().setParam("type", "BUNDLED").execute().getInput(); jsonArray = Json.parse(response).asObject().get("plugins").asArray(); assertThat(jsonArray).hasSize(1); assertThat(jsonArray).extracting(JsonValue::asObject) .extracting(members -> members.get("key").asString()) .containsExactlyInAnyOrder("foo-bundled-1"); // type param == EXTERNAL response = tester.newRequest().setParam("type", "EXTERNAL").execute().getInput(); jsonArray = Json.parse(response).asObject().get("plugins").asArray(); assertThat(jsonArray).hasSize(2); assertThat(jsonArray).extracting(JsonValue::asObject) .extracting(members -> members.get("key").asString()) .containsExactlyInAnyOrder("foo-external-1", "foo-external-2"); } @Test public void empty_fields_are_not_serialized_to_json() throws IOException { when(serverPluginRepository.getPlugins()).thenReturn( singletonList(newInstalledPlugin(new PluginInfo("foo") .setName(null) .setDescription(null) .setLicense(null) .setOrganizationName(null) .setOrganizationUrl(null) .setImplementationBuild(null) .setHomepageUrl(null) .setIssueTrackerUrl(null)))); db.pluginDbTester().insertPlugin( p -> p.setKee("foo"), p -> p.setType(Type.EXTERNAL), p -> p.setUpdatedAt(100L)); String response = tester.newRequest().execute().getInput(); JsonObject json = Json.parse(response).asObject().get("plugins").asArray().get(0).asObject(); assertThat(json.get("key")).isNotNull(); assertThat(json.get("name")).isNotNull(); assertThat(json.get("description")).isNull(); assertThat(json.get("license")).isNull(); assertThat(json.get("organizationName")).isNull(); assertThat(json.get("organizationUrl")).isNull(); assertThat(json.get("homepageUrl")).isNull(); assertThat(json.get("issueTrackerUrl")).isNull(); } private ServerPlugin newInstalledPlugin(PluginInfo plugin) throws IOException { return newInstalledPlugin(plugin, PluginType.BUNDLED); } private ServerPlugin newInstalledPlugin(PluginInfo plugin, PluginType type) throws IOException { FileAndMd5 jar = new FileAndMd5(temp.newFile()); return new ServerPlugin(plugin, type, null, jar, null); } @Test public void return_default_fields() throws Exception { ServerPlugin plugin = newInstalledPlugin(new PluginInfo("foo") .setName("plugName") .setDescription("desc_it") .setVersion(Version.create("1.0")) .setLicense("license_hey") .setOrganizationName("org_name") .setOrganizationUrl("org_url") .setHomepageUrl("homepage_url") .setIssueTrackerUrl("issueTracker_url") .setImplementationBuild("sou_rev_sha1") .setSonarLintSupported(true)); when(serverPluginRepository.getPlugins()).thenReturn(singletonList(plugin)); db.pluginDbTester().insertPlugin( p -> p.setKee(plugin.getPluginInfo().getKey()), p -> p.setType(Type.valueOf(plugin.getType().name())), p -> p.setUpdatedAt(100L)); String response = tester.newRequest().execute().getInput(); verifyNoMoreInteractions(updateCenterMatrixFactory); assertJson(response).isSimilarTo( "{" + " \"plugins\":" + " [" + " {" + " \"key\": \"foo\"," + " \"name\": \"plugName\"," + " \"description\": \"desc_it\"," + " \"version\": \"1.0\"," + " \"license\": \"license_hey\"," + " \"organizationName\": \"org_name\"," + " \"organizationUrl\": \"org_url\",\n" + " \"editionBundled\": false," + " \"homepageUrl\": \"homepage_url\"," + " \"issueTrackerUrl\": \"issueTracker_url\"," + " \"implementationBuild\": \"sou_rev_sha1\"," + " \"sonarLintSupported\": true," + " \"filename\": \"" + plugin.getJar().getFile().getName() + "\"," + " \"hash\": \"" + plugin.getJar().getMd5() + "\"," + " \"updatedAt\": 100" + " }" + " ]" + "}"); } @Test public void category_is_returned_when_in_additional_fields() throws Exception { String jarFilename = getClass().getSimpleName() + "/" + "some.jar"; File jar = new File(getClass().getResource(jarFilename).toURI()); when(serverPluginRepository.getPlugins()).thenReturn(asList( newInstalledPlugin(new PluginInfo("plugKey") .setName("plugName") .setDescription("desc_it") .setVersion(Version.create("1.0")) .setLicense("license_hey") .setOrganizationName("org_name") .setOrganizationUrl("org_url") .setHomepageUrl("homepage_url") .setIssueTrackerUrl("issueTracker_url") .setImplementationBuild("sou_rev_sha1")))); // .setJarFile(jar), new FileAndMd5(jar), null UpdateCenter updateCenter = mock(UpdateCenter.class); when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.of(updateCenter)); when(updateCenter.findAllCompatiblePlugins()).thenReturn( asList( Plugin.factory("plugKey") .setCategory("cat_1"))); db.pluginDbTester().insertPlugin( p -> p.setKee("plugKey"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdplugKey"), p -> p.setUpdatedAt(111111L)); String response = tester.newRequest() .setParam(WebService.Param.FIELDS, "category") .execute().getInput(); assertJson(response).isSimilarTo( "{" + " \"plugins\":" + " [" + " {" + " \"key\": \"plugKey\"," + " \"name\": \"plugName\"," + " \"description\": \"desc_it\"," + " \"version\": \"1.0\"," + " \"category\":\"cat_1\"," + " \"license\": \"license_hey\"," + " \"organizationName\": \"org_name\"," + " \"organizationUrl\": \"org_url\",\n" + " \"editionBundled\": false," + " \"homepageUrl\": \"homepage_url\"," + " \"issueTrackerUrl\": \"issueTracker_url\"," + " \"implementationBuild\": \"sou_rev_sha1\"" + " }" + " ]" + "}"); } @Test public void plugins_are_sorted_by_name_then_key_and_only_one_plugin_can_have_a_specific_name() throws IOException { when(serverPluginRepository.getPlugins()).thenReturn( asList( plugin("A", "name2"), plugin("B", "name1"), plugin("C", "name0"), plugin("D", "name0"))); db.pluginDbTester().insertPlugin( p -> p.setKee("A"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdA"), p -> p.setUpdatedAt(111111L)); db.pluginDbTester().insertPlugin( p -> p.setKee("B"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdB"), p -> p.setUpdatedAt(222222L)); db.pluginDbTester().insertPlugin( p -> p.setKee("C"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdC"), p -> p.setUpdatedAt(333333L)); db.pluginDbTester().insertPlugin( p -> p.setKee("D"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdD"), p -> p.setUpdatedAt(444444L)); String resp = tester.newRequest().execute().getInput(); assertJson(resp).withStrictArrayOrder().isSimilarTo( "{" + " \"plugins\":" + " [" + " {\"key\": \"C\"}" + "," + " {\"key\": \"D\"}" + "," + " {\"key\": \"B\"}" + "," + " {\"key\": \"A\"}" + " ]" + "}"); } @Test @UseDataProvider("editionBundledLicenseValues") public void commercial_plugins_from_SonarSource_has_flag_editionBundled_true_based_on_jar_info(String license) throws Exception { String jarFilename = getClass().getSimpleName() + "/" + "some.jar"; Random random = new Random(); String organization = random.nextBoolean() ? "SonarSource" : "SONARSOURCE"; String pluginKey = "plugKey"; File jar = new File(getClass().getResource(jarFilename).toURI()); when(serverPluginRepository.getPlugins()).thenReturn(asList( new ServerPlugin(new PluginInfo(pluginKey) .setName("plugName") .setVersion(Version.create("1.0")) .setLicense(license) .setOrganizationName(organization) .setImplementationBuild("sou_rev_sha1"), PluginType.BUNDLED, null, new FileAndMd5(jar), null))); db.pluginDbTester().insertPlugin( p -> p.setKee(pluginKey), p -> p.setType(Type.BUNDLED), p -> p.setFileHash("abcdplugKey"), p -> p.setUpdatedAt(111111L)); // ensure flag editionBundled is computed from jar info by enabling datacenter with other organization and license values UpdateCenter updateCenter = mock(UpdateCenter.class); when(updateCenterMatrixFactory.getUpdateCenter(false)).thenReturn(Optional.of(updateCenter)); when(updateCenter.findAllCompatiblePlugins()).thenReturn( singletonList( Plugin.factory(pluginKey) .setOrganization("foo") .setLicense("bar") .setCategory("cat_1"))); String response = tester.newRequest().execute().getInput(); verifyNoInteractions(updateCenterMatrixFactory); assertJson(response) .isSimilarTo("{" + " \"plugins\":" + " [" + " {" + " \"key\": \"plugKey\"," + " \"name\": \"plugName\"," + " \"license\": \"" + license + "\"," + " \"organizationName\": \"" + organization + "\"," + " \"editionBundled\": true" + " }" + " ]" + "}"); } @Test public void only_one_plugin_can_have_a_specific_name_and_key() throws IOException { when(serverPluginRepository.getPlugins()).thenReturn( asList( plugin("A", "name2"), plugin("A", "name2"))); db.pluginDbTester().insertPlugin( p -> p.setKee("A"), p -> p.setType(Type.EXTERNAL), p -> p.setFileHash("abcdA"), p -> p.setUpdatedAt(111111L)); String response = tester.newRequest().execute().getInput(); assertJson(response).withStrictArrayOrder().isSimilarTo( "{" + " \"plugins\":" + " [" + " {\"key\": \"A\"}" + " ]" + "}"); assertThat(response).containsOnlyOnce("name2"); } @Test public void fail_if_not_logged_in() { userSession.anonymous(); TestRequest testRequest = tester.newRequest(); assertThatThrownBy(testRequest::execute) .isInstanceOf(ForbiddenException.class); } private ServerPlugin plugin(String key, String name) throws IOException { File file = temp.newFile(); PluginInfo info = new PluginInfo(key) .setName(name) .setVersion(Version.create("1.0")); info.setJarFile(file); return new ServerPlugin(info, PluginType.BUNDLED, null, new FileAndMd5(file), null); } }
17,157
36.544858
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/BulkDeleteActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.net.HttpURLConnection; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.RandomUtils; import org.joda.time.DateTime; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.PortfolioData; import org.sonar.db.component.ProjectData; import org.sonar.db.entity.EntityDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentCleanerService; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.project.DeletedProject; import org.sonar.server.project.Project; import org.sonar.server.project.ProjectLifeCycleListeners; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.sonar.api.utils.DateUtils.formatDate; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS; public class BulkDeleteActionIT { @Rule public final DbTester db = DbTester.create(System2.INSTANCE); @Rule public final UserSessionRule userSession = UserSessionRule.standalone().logIn(); private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class); private final DbClient dbClient = db.getDbClient(); private final ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class); private final BulkDeleteAction underTest = new BulkDeleteAction(componentCleanerService, dbClient, userSession, projectLifeCycleListeners); private final WsActionTester ws = new WsActionTester(underTest); @Test public void delete_projects() { userSession.addPermission(ADMINISTER); ProjectData projectData1ToDelete = db.components().insertPrivateProject(); ProjectDto project1ToDelete = projectData1ToDelete.getProjectDto(); ProjectData projectData2ToDelete = db.components().insertPrivateProject(); ProjectDto project2ToDelete = projectData2ToDelete.getProjectDto(); ComponentDto toKeep = db.components().insertPrivateProject().getMainBranchComponent(); TestResponse result = ws.newRequest() .setParam(PARAM_PROJECTS, project1ToDelete.getKey() + "," + project2ToDelete.getKey()) .execute(); assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT); assertThat(result.getInput()).isEmpty(); verifyEntityDeleted(project1ToDelete, project2ToDelete); verifyListenersOnProjectsDeleted(projectData1ToDelete, projectData2ToDelete); } @Test public void delete_projects_by_keys() { userSession.addPermission(ADMINISTER); ProjectData toDeleteInOrg1 = db.components().insertPrivateProject(); ProjectData toDeleteInOrg2 = db.components().insertPrivateProject(); ComponentDto toKeep = db.components().insertPrivateProject().getMainBranchComponent(); ws.newRequest() .setParam(PARAM_PROJECTS, toDeleteInOrg1.getProjectDto().getKey() + "," + toDeleteInOrg2.getProjectDto().getKey()) .execute(); verifyEntityDeleted(toDeleteInOrg1.getProjectDto(), toDeleteInOrg2.getProjectDto()); verifyListenersOnProjectsDeleted(toDeleteInOrg1, toDeleteInOrg2); } @Test public void throw_IllegalArgumentException_if_request_without_any_parameters() { userSession.addPermission(ADMINISTER); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); try { TestRequest request = ws.newRequest(); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("At least one parameter among analyzedBefore, projects and q must be provided"); } finally { verifyNoDeletions(); verifyNoMoreInteractions(projectLifeCycleListeners); } } @Test public void projects_that_dont_exist_are_ignored_and_dont_break_bulk_deletion() { userSession.addPermission(ADMINISTER); ProjectData toDelete1 = db.components().insertPrivateProject(); ProjectData toDelete2 = db.components().insertPrivateProject(); ws.newRequest() .setParam("projects", toDelete1.getProjectDto().getKey() + ",missing," + toDelete2.getProjectDto().getKey() + ",doesNotExist") .execute(); verifyEntityDeleted(toDelete1.getProjectDto(), toDelete2.getProjectDto()); verifyListenersOnProjectsDeleted(toDelete1, toDelete2); } @Test public void old_projects() { userSession.logIn().addPermission(ADMINISTER); long aLongTimeAgo = 1_000_000_000L; long recentTime = 3_000_000_000L; ProjectData oldProjectData = db.components().insertPublicProject(); ProjectDto oldProject = oldProjectData.getProjectDto(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(oldProjectData.getMainBranchComponent()).setCreatedAt(aLongTimeAgo)); ProjectData recentProjectData = db.components().insertPublicProject(); ProjectDto recentProject = recentProjectData.getProjectDto(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(recentProjectData.getMainBranchComponent()).setCreatedAt(aLongTimeAgo)); ComponentDto branch = db.components().insertProjectBranch(recentProjectData.getMainBranchComponent()); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(branch).setCreatedAt(recentTime)); db.commit(); ws.newRequest() .setParam(PARAM_ANALYZED_BEFORE, formatDate(new Date(recentTime))) .execute(); verifyEntityDeleted(oldProject); verifyListenersOnProjectsDeleted(oldProjectData); } @Test public void provisioned_projects() { userSession.logIn().addPermission(ADMINISTER); ProjectData provisionedProject = db.components().insertPrivateProject(); ProjectData analyzedProjectData = db.components().insertPrivateProject(); ProjectDto analyzedProject = analyzedProjectData.getProjectDto(); db.components().insertSnapshot(newAnalysis(analyzedProjectData.getMainBranchComponent())); ws.newRequest().setParam(PARAM_PROJECTS, provisionedProject.getProjectDto().getKey() + "," + analyzedProject.getKey()).setParam(PARAM_ON_PROVISIONED_ONLY, "true").execute(); verifyEntityDeleted(provisionedProject.getProjectDto()); verifyListenersOnProjectsDeleted(provisionedProject); } @Test public void delete_more_than_50_projects() { userSession.logIn().addPermission(ADMINISTER); ProjectData[] projects = IntStream.range(0, 55).mapToObj(i -> db.components().insertPrivateProject()).toArray(ProjectData[]::new); List<String> projectKeys = Stream.of(projects).map(ProjectData::getProjectDto).map(ProjectDto::getKey).toList(); ws.newRequest().setParam(PARAM_PROJECTS, String.join(",", projectKeys)).execute(); verifyEntityDeleted(Stream.of(projects).map(ProjectData::getProjectDto).toArray(ProjectDto[]::new)); verifyListenersOnProjectsDeleted(projects); } @Test public void projects_and_views() { userSession.logIn().addPermission(ADMINISTER); ProjectData project = db.components().insertPrivateProject(); ComponentDto view = db.components().insertPrivatePortfolio(); PortfolioDto portfolioDto = db.components().getPortfolioDto(view); ws.newRequest() .setParam(PARAM_PROJECTS, project.getProjectDto().getKey() + "," + view.getKey()) .setParam(PARAM_QUALIFIERS, String.join(",", Qualifiers.PROJECT, Qualifiers.VIEW)) .execute(); verifyEntityDeleted(project.getProjectDto(), portfolioDto); verifyListenersOnProjectsDeleted(project, portfolioDto); } @Test public void delete_by_key_query_with_partial_match_case_insensitive() { userSession.logIn().addPermission(ADMINISTER); ProjectData matchKeyProject = db.components().insertPrivateProject(p -> p.setKey("project-_%-key")); ProjectData matchUppercaseKeyProject = db.components().insertPrivateProject(p -> p.setKey("PROJECT-_%-KEY")); ProjectDto noMatchProject = db.components().insertPrivateProject(p -> p.setKey("project-key-without-escaped-characters")).getProjectDto(); ws.newRequest().setParam(Param.TEXT_QUERY, "JeCt-_%-k").execute(); verifyEntityDeleted(matchKeyProject.getProjectDto(), matchUppercaseKeyProject.getProjectDto()); verifyListenersOnProjectsDeleted(matchKeyProject, matchUppercaseKeyProject); } /** * SONAR-10356 */ @Test public void delete_only_the_1000_first_projects() { userSession.logIn().addPermission(ADMINISTER); List<String> keys = IntStream.range(0, 1_010).mapToObj(i -> "key" + i).toList(); keys.forEach(key -> db.components().insertPrivateProject(p -> p.setKey(key)).getMainBranchComponent()); ws.newRequest() .setParam("projects", StringUtils.join(keys, ",")) .execute(); verify(componentCleanerService, times(1_000)).deleteEntity(any(DbSession.class), any(EntityDto.class)); ArgumentCaptor<Set<DeletedProject>> projectsCaptor = ArgumentCaptor.forClass(Set.class); verify(projectLifeCycleListeners).onProjectsDeleted(projectsCaptor.capture()); assertThat(projectsCaptor.getValue()).hasSize(1_000); } @Test public void projectLifeCycleListeners_onProjectsDeleted_called_even_if_delete_fails() { userSession.logIn().addPermission(ADMINISTER); ProjectData project1 = db.components().insertPrivateProject(); ProjectData project2 = db.components().insertPrivateProject(); ProjectData project3 = db.components().insertPrivateProject(); ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class); RuntimeException expectedException = new RuntimeException("Faking delete failing on 2nd project"); doNothing() .doThrow(expectedException) .when(componentCleanerService) .deleteEntity(any(), any(ProjectDto.class)); try { ws.newRequest() .setParam("projects", project1.getProjectDto().getKey() + "," + project2.getProjectDto().getKey() + "," + project3.getProjectDto().getKey()) .execute(); } catch (RuntimeException e) { assertThat(e).isSameAs(expectedException); verifyListenersOnProjectsDeleted(project1, project2, project3); } } @Test public void global_administrator_deletes_projects_by_keys() { userSession.logIn().addPermission(ADMINISTER); ProjectData toDelete1 = db.components().insertPrivateProject(); ProjectData toDelete2 = db.components().insertPrivateProject(); ws.newRequest() .setParam("projects", toDelete1.getProjectDto().getKey() + "," + toDelete2.getProjectDto().getKey()) .execute(); verifyEntityDeleted(toDelete1.getProjectDto(), toDelete2.getProjectDto()); verifyListenersOnProjectsDeleted(toDelete1, toDelete2); } @Test public void should_throw_IAE_when_providing_future_date_as_analyzed_before_date() { userSession.logIn().addPermission(ADMINISTER); Date now = new Date(); Date futureDate = new DateTime(now).plusDays(RandomUtils.nextInt() + 1).toDate(); ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(project1).setCreatedAt(now.getTime())); ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(project2).setCreatedAt(now.getTime())); db.commit(); TestRequest request = ws.newRequest().setParam(PARAM_ANALYZED_BEFORE, formatDate(futureDate)); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Provided value for parameter analyzedBefore must not be a future date"); } @Test public void throw_UnauthorizedException_if_not_logged_in() { userSession.anonymous(); TestRequest request = ws.newRequest().setParam("ids", "whatever-the-uuid"); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class) .hasMessage("Authentication is required"); verifyNoDeletions(); verifyNoMoreInteractions(projectLifeCycleListeners); } private void verifyEntityDeleted(EntityDto... entities) { ArgumentCaptor<EntityDto> argument = ArgumentCaptor.forClass(EntityDto.class); verify(componentCleanerService, times(entities.length)).deleteEntity(any(DbSession.class), argument.capture()); for (EntityDto entity : entities) { assertThat(argument.getAllValues()).extracting(EntityDto::getUuid).contains(entity.getUuid()); } } private void verifyNoDeletions() { verifyNoMoreInteractions(componentCleanerService); } private void verifyListenersOnProjectsDeleted(ProjectData projectData, PortfolioDto portfolioDto) { Map<EntityDto, String> entityWithBranh = new HashMap<>(); entityWithBranh.put(projectData.getProjectDto(), projectData.getMainBranchDto().getUuid()); entityWithBranh.put(portfolioDto, null); verifyListenersOnProjectsDeleted(entityWithBranh); } private void verifyListenersOnProjectsDeleted(ProjectData... projectData) { verifyListenersOnProjectsDeleted(Arrays.stream(projectData).collect(Collectors.toMap(ProjectData::getProjectDto, data -> data.getMainBranchDto().getUuid()))); } private void verifyListenersOnProjectsDeleted(PortfolioData... portfolioData) { verifyListenersOnProjectsDeleted(Arrays.stream(portfolioData).collect(Collectors.toMap(PortfolioData::getPortfolioDto, null))); } private void verifyListenersOnProjectsDeleted(Map<EntityDto, String> entityWithBranchUuid) { verify(projectLifeCycleListeners) .onProjectsDeleted(entityWithBranchUuid.entrySet() .stream().map(entry -> new DeletedProject(Project.from(entry.getKey()), entry.getValue())).collect(Collectors.toSet())); } }
15,942
43.909859
177
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/CreateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import com.google.common.base.Strings; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.es.Indexers; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.l18n.I18nRule; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.project.ws.CreateAction.Builder; import org.sonar.server.project.ws.CreateAction.CreateRequest; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects.CreateWsResponse; import org.sonarqube.ws.Projects.CreateWsResponse.Project; import static java.util.Optional.ofNullable; import static java.util.stream.IntStream.rangeClosed; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS; import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH; import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION; import static org.sonar.server.project.Visibility.PRIVATE; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.WsRequest.Method.POST; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_MAIN_BRANCH; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NAME; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY; public class CreateActionIT { private static final String DEFAULT_PROJECT_KEY = "project-key"; private static final String DEFAULT_PROJECT_NAME = "project-name"; private static final String MAIN_BRANCH = "main-branch"; private final System2 system2 = System2.INSTANCE; @Rule public final DbTester db = DbTester.create(system2); @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public final I18nRule i18n = new I18nRule().put("qualifier.TRK", "Project"); private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class); private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class); private final TestIndexers projectIndexers = new TestIndexers(); private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class); private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private final NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider); private final WsActionTester ws = new WsActionTester( new CreateAction( db.getDbClient(), userSession, new ComponentUpdater(db.getDbClient(), i18n, system2, permissionTemplateService, new FavoriteUpdater(db.getDbClient()), projectIndexers, new SequenceUuidFactory(), defaultBranchNameResolver, true), projectDefaultVisibility, defaultBranchNameResolver, newCodeDefinitionResolver)); @Before public void before() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PUBLIC); when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); } @Test public void create_project() { userSession.addPermission(PROVISION_PROJECTS); CreateWsResponse response = call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .build()); assertThat(response.getProject()) .extracting(Project::getKey, Project::getName, Project::getQualifier, Project::getVisibility) .containsOnly(DEFAULT_PROJECT_KEY, DEFAULT_PROJECT_NAME, "TRK", "public"); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(component) .extracting(ComponentDto::getKey, ComponentDto::name, ComponentDto::qualifier, ComponentDto::scope, ComponentDto::isPrivate) .containsOnly(DEFAULT_PROJECT_KEY, DEFAULT_PROJECT_NAME, "TRK", "PRJ", false); BranchDto branch = db.getDbClient().branchDao().selectByUuid(db.getSession(), component.branchUuid()).get(); assertThat(branch) .extracting(BranchDto::getKey) .isEqualTo(MAIN_BRANCH); projectIndexers.hasBeenCalledForEntity(branch.getProjectUuid(), Indexers.EntityEvent.CREATION); } @Test public void apply_project_visibility_public() { userSession.addPermission(PROVISION_PROJECTS); CreateWsResponse result = ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .setParam("visibility", "public") .executeProtobuf(CreateWsResponse.class); assertThat(result.getProject().getVisibility()).isEqualTo("public"); } @Test public void apply_project_visibility_private() { userSession.addPermission(PROVISION_PROJECTS); CreateWsResponse result = ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .setParam("visibility", PRIVATE.getLabel()) .executeProtobuf(CreateWsResponse.class); assertThat(result.getProject().getVisibility()).isEqualTo("private"); } @Test public void apply_default_project_visibility_public() { when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PUBLIC); userSession.addPermission(PROVISION_PROJECTS); CreateWsResponse result = ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .executeProtobuf(CreateWsResponse.class); assertThat(result.getProject().getVisibility()).isEqualTo("public"); } @Test public void apply_default_project_visibility_private() { when(projectDefaultVisibility.get(any())).thenReturn(PRIVATE); userSession.addPermission(PROVISION_PROJECTS); CreateWsResponse result = ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .executeProtobuf(CreateWsResponse.class); assertThat(result.getProject().getVisibility()).isEqualTo("private"); } @Test public void abbreviate_project_name_if_very_long() { userSession.addPermission(PROVISION_PROJECTS); String longName = Strings.repeat("a", 1_000); ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", longName) .executeProtobuf(CreateWsResponse.class); assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get().name()) .isEqualTo(Strings.repeat("a", 497) + "..."); } @Test public void add_project_to_user_favorites_if_project_creator_is_defined_in_permission_template() { UserDto user = db.users().insertUser(); when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ProjectDto.class))).thenReturn(true); userSession.logIn(user).addPermission(PROVISION_PROJECTS); ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .executeProtobuf(CreateWsResponse.class); ProjectDto project = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.favorites().hasFavorite(project, user.getUuid())).isTrue(); } @Test public void do_not_add_project_to_user_favorites_if_project_creator_is_defined_in_permission_template_and_already_100_favorites() { UserDto user = db.users().insertUser(); when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ProjectDto.class))).thenReturn(true); rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject().getProjectDto(), user.getUuid(), user.getLogin())); userSession.logIn(user).addPermission(PROVISION_PROJECTS); ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .executeProtobuf(CreateWsResponse.class); ProjectDto project = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.favorites().hasNoFavorite(project)).isTrue(); } @Test public void fail_when_project_already_exists() { db.components().insertPublicProject(project -> project.setKey(DEFAULT_PROJECT_KEY)).getMainBranchComponent(); userSession.addPermission(PROVISION_PROJECTS); CreateRequest request = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(BadRequestException.class); } @Test public void fail_when_invalid_project_key() { userSession.addPermission(PROVISION_PROJECTS); CreateRequest request = CreateRequest.builder() .setProjectKey("project%Key") .setName(DEFAULT_PROJECT_NAME) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(BadRequestException.class) .hasMessage("Malformed key for Project: 'project%Key'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least " + "one non-digit."); } @Test public void fail_when_missing_project_parameter() { userSession.addPermission(PROVISION_PROJECTS); assertThatThrownBy(() -> call(null, DEFAULT_PROJECT_NAME, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'project' parameter is missing"); } @Test public void fail_when_missing_name_parameter() { userSession.addPermission(PROVISION_PROJECTS); assertThatThrownBy(() -> call(DEFAULT_PROJECT_KEY, null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'name' parameter is missing"); } @Test public void fail_when_missing_create_project_permission() { CreateRequest request = CreateRequest.builder().setProjectKey(DEFAULT_PROJECT_KEY).setName(DEFAULT_PROJECT_NAME) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void test_example() { userSession.addPermission(PROVISION_PROJECTS); String result = ws.newRequest() .setParam("project", DEFAULT_PROJECT_KEY) .setParam("name", DEFAULT_PROJECT_NAME) .execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("create-example.json")); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("create"); assertThat(definition.since()).isEqualTo("4.0"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder( PARAM_VISIBILITY, PARAM_NAME, PARAM_PROJECT, PARAM_MAIN_BRANCH, PARAM_NEW_CODE_DEFINITION_TYPE, PARAM_NEW_CODE_DEFINITION_VALUE); WebService.Param visibilityParam = definition.param(PARAM_VISIBILITY); assertThat(visibilityParam.description()).isNotEmpty(); assertThat(visibilityParam.isInternal()).isFalse(); assertThat(visibilityParam.isRequired()).isFalse(); assertThat(visibilityParam.since()).isEqualTo("6.4"); assertThat(visibilityParam.possibleValues()).containsExactlyInAnyOrder("private", "public"); WebService.Param project = definition.param(PARAM_PROJECT); assertThat(project.isRequired()).isTrue(); assertThat(project.maximumLength()).isEqualTo(400); WebService.Param name = definition.param(PARAM_NAME); assertThat(name.isRequired()).isTrue(); assertThat(name.description()).isEqualTo("Name of the project. If name is longer than 500, it is abbreviated."); WebService.Param ncdType = definition.param(PARAM_NEW_CODE_DEFINITION_TYPE); assertThat(ncdType.isRequired()).isFalse(); assertThat(ncdType.description()).isEqualTo(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION); WebService.Param ncdValue = definition.param(PARAM_NEW_CODE_DEFINITION_VALUE); assertThat(ncdValue.isRequired()).isFalse(); assertThat(ncdValue.description()).isEqualTo(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION); } @Test public void fail_when_set_null_project_name_on_create_request_builder() { Builder builder = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY); assertThatThrownBy(() -> builder.setName(null)) .isInstanceOf(NullPointerException.class); } @Test public void fail_when_set_null_project_key_on_create_request_builder() { Builder builder = CreateRequest.builder() .setName(DEFAULT_PROJECT_NAME); assertThatThrownBy(() -> builder.setProjectKey(null)) .isInstanceOf(NullPointerException.class); } @Test public void fail_when_project_key_not_set_on_create_request_builder() { CreateRequest.builder() .setName(DEFAULT_PROJECT_NAME); Builder builder = CreateRequest.builder() .setName(DEFAULT_PROJECT_NAME); assertThatThrownBy(builder::build) .isInstanceOf(NullPointerException.class); } @Test public void fail_when_project_name_not_set_on_create_request_builder() { Builder builder = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY); assertThatThrownBy(builder::build) .isInstanceOf(NullPointerException.class); } @Test public void set_default_branch_name_for_reference_branch_NCD_when_no_main_branch_provided() { userSession.addPermission(PROVISION_PROJECTS); String otherBranchName = "otherBranchName"; when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(otherBranchName); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setNewCodeDefinitionType(REFERENCE_BRANCH.name()) .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), component.uuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, otherBranchName); } @Test public void set_main_branch_name_for_reference_branch_NCD() { userSession.addPermission(PROVISION_PROJECTS); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType(REFERENCE_BRANCH.name()) .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), component.uuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(REFERENCE_BRANCH, MAIN_BRANCH); } @Test public void set_new_code_definition_on_project_creation() { userSession.addPermission(PROVISION_PROJECTS); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType(NUMBER_OF_DAYS.name()) .setNewCodeDefinitionValue("30") .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), component.uuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue) .containsExactly(NUMBER_OF_DAYS, "30"); } @Test public void set_new_code_definition_branch_for_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); userSession.addPermission(PROVISION_PROJECTS); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType(NUMBER_OF_DAYS.name()) .setNewCodeDefinitionValue("30") .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), component.uuid(), component.uuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", component.uuid()); } @Test public void throw_IAE_if_setting_is_not_cayc_compliant() { userSession.addPermission(PROVISION_PROJECTS); CreateRequest request = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType(NUMBER_OF_DAYS.name()) .setNewCodeDefinitionValue("99") .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Failed to set the New Code Definition. The given value is not compatible with the Clean as You Code methodology. " + "Please refer to the documentation for compliant options."); assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY)) .isEmpty(); } @Test public void throw_IAE_if_setting_is_new_code_definition_value_provided_without_type() { userSession.addPermission(PROVISION_PROJECTS); CreateRequest request = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionValue("99") .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("New code definition type is required when new code definition value is provided"); assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY)) .isEmpty(); assertThat(db.getDbClient().newCodePeriodDao().selectAll(db.getSession())).isEmpty(); } @Test public void set_new_code_definition_for_project_for_developer_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); userSession.addPermission(PROVISION_PROJECTS); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType(NUMBER_OF_DAYS.name()) .setNewCodeDefinitionValue("30") .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), component.uuid())) .isPresent() .get() .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid) .containsExactly(NUMBER_OF_DAYS, "30", null); } @Test public void do_not_create_project_when_ncdType_invalid() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); userSession.addPermission(PROVISION_PROJECTS); CreateRequest request = CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .setNewCodeDefinitionType("InvalidType") .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class); assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY)) .isEmpty(); } @Test public void do_not_set_new_code_definition_when_ncdType_not_provided() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER)); userSession.addPermission(PROVISION_PROJECTS); call(CreateRequest.builder() .setProjectKey(DEFAULT_PROJECT_KEY) .setName(DEFAULT_PROJECT_NAME) .setMainBranchKey(MAIN_BRANCH) .build()); ComponentDto component = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get(); assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), component.uuid())) .isEmpty(); } private CreateWsResponse call(CreateRequest request) { return call(request.getProjectKey(), request.getName(), request.getMainBranchKey(), request.getNewCodeDefinitionType(), request.getNewCodeDefinitionValue()); } private CreateWsResponse call(@Nullable String projectKey, @Nullable String projectName, @Nullable String mainBranch, @Nullable String newCodeDefinitionType, @Nullable String newCodeDefinitionValue) { TestRequest httpRequest = ws.newRequest() .setMethod(POST.name()); ofNullable(projectKey).ifPresent(key -> httpRequest.setParam("project", key)); ofNullable(projectName).ifPresent(name -> httpRequest.setParam("name", name)); ofNullable(mainBranch).ifPresent(name -> httpRequest.setParam("mainBranch", mainBranch)); ofNullable(newCodeDefinitionType).ifPresent(type -> httpRequest.setParam(PARAM_NEW_CODE_DEFINITION_TYPE, type)); ofNullable(newCodeDefinitionValue).ifPresent(value -> httpRequest.setParam(PARAM_NEW_CODE_DEFINITION_VALUE, value)); return httpRequest.executeProtobuf(CreateWsResponse.class); } }
24,393
40.486395
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/DeleteActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.db.webhook.WebhookDbTester; import org.sonar.db.webhook.WebhookDto; import org.sonar.server.component.ComponentCleanerService; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.project.DeletedProject; import org.sonar.server.project.Project; import org.sonar.server.project.ProjectLifeCycleListeners; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.server.component.TestComponentFinder.from; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT; public class DeleteActionIT { private final System2 system2 = System2.INSTANCE; @Rule public final DbTester db = DbTester.create(system2); @Rule public final UserSessionRule userSessionRule = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final WebhookDbTester webhookDbTester = db.webhooks(); private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class); private final ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class); private final DeleteAction underTest = new DeleteAction( componentCleanerService, from(db), dbClient, userSessionRule, projectLifeCycleListeners); private final WsActionTester tester = new WsActionTester(underTest); @Test public void global_administrator_deletes_project_by_key() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto rootComponent = projectData.getMainBranchComponent(); userSessionRule.logIn().addPermission(GlobalPermission.ADMINISTER); call(tester.newRequest().setParam(PARAM_PROJECT, rootComponent.getKey())); assertThat(verifyDeletedKey()).isEqualTo(rootComponent.getKey()); Project from = Project.from(projectData.getProjectDto()); String mainBranchUuid = projectData.getMainBranchDto().getUuid(); verify(projectLifeCycleListeners).onProjectsDeleted(singleton(new DeletedProject(from, mainBranchUuid))); } @Test public void project_administrator_deletes_the_project_by_key() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); userSessionRule.logIn().addProjectPermission(UserRole.ADMIN, projectData.getProjectDto()); call(tester.newRequest().setParam(PARAM_PROJECT, project.getKey())); assertThat(verifyDeletedKey()).isEqualTo(project.getKey()); verify(projectLifeCycleListeners).onProjectsDeleted(singleton(new DeletedProject(Project.from(projectData.getProjectDto()),projectData.getMainBranchDto().getUuid()))); } @Test public void project_deletion_also_ensure_that_homepage_on_this_project_if_it_exists_is_cleared() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); UserDto insert = dbClient.userDao().insert(dbSession, newUserDto().setHomepageType("PROJECT").setHomepageParameter(projectData.projectUuid())); dbSession.commit(); userSessionRule.logIn().addProjectPermission(UserRole.ADMIN, projectData.getProjectDto()); DeleteAction underTest = new DeleteAction( new ComponentCleanerService(dbClient, new TestIndexers()), from(db), dbClient, userSessionRule, projectLifeCycleListeners); new WsActionTester(underTest) .newRequest() .setParam(PARAM_PROJECT, project.getKey()) .execute(); UserDto userReloaded = dbClient.userDao().selectByUuid(dbSession, insert.getUuid()); assertThat(userReloaded.getHomepageType()).isNull(); assertThat(userReloaded.getHomepageParameter()).isNull(); } @Test public void project_deletion_also_ensure_that_webhooks_on_this_project_if_they_exists_are_deleted() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); webhookDbTester.insertWebhook(project); webhookDbTester.insertWebhook(project); webhookDbTester.insertWebhook(project); webhookDbTester.insertWebhook(project); userSessionRule.logIn().addProjectPermission(UserRole.ADMIN, project); DeleteAction underTest = new DeleteAction( new ComponentCleanerService(dbClient, new TestIndexers()), from(db), dbClient, userSessionRule, projectLifeCycleListeners); new WsActionTester(underTest) .newRequest() .setParam(PARAM_PROJECT, project.getKey()) .execute(); List<WebhookDto> webhookDtos = dbClient.webhookDao().selectByProject(dbSession, project); assertThat(webhookDtos).isEmpty(); } @Test public void return_403_if_not_project_admin_nor_org_admin() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSessionRule.logIn() .addProjectPermission(UserRole.CODEVIEWER, project) .addProjectPermission(UserRole.ISSUE_ADMIN, project) .addProjectPermission(UserRole.USER, project); TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, project.getKey()); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void return_401_if_not_logged_in() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSessionRule.anonymous(); TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, project.getKey()); assertThatThrownBy(() -> call(request)) .isInstanceOf(UnauthorizedException.class); } private String verifyDeletedKey() { ArgumentCaptor<ProjectDto> argument = ArgumentCaptor.forClass(ProjectDto.class); verify(componentCleanerService).deleteEntity(any(DbSession.class), argument.capture()); return argument.getValue().getKey(); } private void call(TestRequest request) { TestResponse result = request.execute(); result.assertNoContent(); } }
7,871
41.096257
171
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/ProjectFinderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.server.project.ws.ProjectFinder.Project; import org.sonar.server.tester.UserSessionRule; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.web.UserRole.SCAN; import static org.sonar.server.project.ws.ProjectFinder.SearchResult; public class ProjectFinderIT { @Rule public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final ProjectFinder underTest = new ProjectFinder(db.getDbClient(), userSession); @Test public void selected_projects() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject().getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2); List<Project> projects = underTest.search(db.getSession(), "").getProjects(); assertThat(projects) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple(project1.getKey(), project1.getName()), tuple(project2.getKey(), project2.getName())); } @Test public void sort_project_by_name() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Projet Trois")).getProjectDto(); ProjectDto project4 = db.components().insertPrivateProject(p -> p.setKey("project:four").setName("Projet Quatre")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); assertThat(underTest.search(db.getSession(), "projet") .getProjects()) .extracting(Project::getName) .containsExactly("Projet Deux", "Projet Quatre", "Projet Trois", "Projet Un"); } @Test public void projects_are_filtered_by_permissions() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Projet Trois")).getProjectDto(); ProjectDto project4 = db.components().insertPrivateProject(p -> p.setKey("project:four").setName("Projet Quatre")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:five").setName("Projet Cinq")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); SearchResult result = underTest.search(db.getSession(), null); assertThat(result.getProjects()) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple("project:one", "Projet Un"), tuple("project:two", "Projet Deux"), tuple("project:three", "Projet Trois"), tuple("project:four", "Projet Quatre")); } @Test public void projects_are_not_filtered_due_to_global_scan_permission() { db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Projet Trois")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:four").setName("Projet Quatre")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:five").setName("Projet Cinq")).getProjectDto(); userSession.addPermission(GlobalPermission.SCAN); SearchResult result = underTest.search(db.getSession(), null); assertThat(result.getProjects()) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple("project:one", "Projet Un"), tuple("project:two", "Projet Deux"), tuple("project:three", "Projet Trois"), tuple("project:four", "Projet Quatre"), tuple("project:five", "Projet Cinq")); } @Test public void search_by_query_on_name_case_insensitive() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Projet Trois")).getProjectDto(); ProjectDto project4 = db.components().insertPrivateProject(p -> p.setKey("project:four").setName("Projet Quatre")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); assertThat(underTest.search(db.getSession(), "projet") .getProjects()) .extracting(Project::getKey) .containsExactlyInAnyOrder("project:one", "project:two", "project:three", "project:four"); assertThat(underTest.search(db.getSession(), "un") .getProjects()) .extracting(Project::getKey) .containsExactlyInAnyOrder("project:one"); assertThat(underTest.search(db.getSession(), "TROIS") .getProjects()) .extracting(Project::getKey) .containsExactlyInAnyOrder("project:three"); } }
6,737
46.787234
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import com.google.common.base.Joiner; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.DateUtils; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Projects.SearchWsResponse; import org.sonarqube.ws.Projects.SearchWsResponse.Component; import org.sonarqube.ws.client.component.ComponentsWsParameters; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.db.component.ComponentTesting.newDirectory; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY; public class SearchActionIT { private static final String PROJECT_KEY_1 = "project1"; private static final String PROJECT_KEY_2 = "project2"; private static final String PROJECT_KEY_3 = "project3"; @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public final DbTester db = DbTester.create(); private final WsActionTester ws = new WsActionTester(new SearchAction(db.getDbClient(), userSession)); @Test public void search_by_key_query_with_partial_match_case_insensitive() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey("project-_%-key")).getMainBranchComponent(); db.components().insertPrivateProject(p -> p.setKey("PROJECT-_%-KEY")).getMainBranchComponent(); db.components().insertPrivateProject(p -> p.setKey("project-key-without-escaped-characters")).getMainBranchComponent(); SearchWsResponse response = call(SearchRequest.builder().setQuery("JeCt-_%-k").build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly("project-_%-key", "PROJECT-_%-KEY"); } @Test public void search_private_projects() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey("private-key")).getMainBranchComponent(); db.components().insertPublicProject(p -> p.setKey("public-key")).getMainBranchComponent(); SearchWsResponse response = call(SearchRequest.builder().setVisibility("private").build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly("private-key"); } @Test public void search_public_projects() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey("private-key")).getMainBranchComponent(); db.components().insertPublicProject(p -> p.setKey("public-key")).getMainBranchComponent(); SearchWsResponse response = call(SearchRequest.builder().setVisibility("public").build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly("public-key"); } @Test public void search_projects_when_no_qualifier_set() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_1)).getMainBranchComponent(); db.components().insertPublicPortfolio(); SearchWsResponse response = call(SearchRequest.builder().build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1); } @Test public void search_projects() { userSession.addPermission(ADMINISTER); ProjectData project = db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_1)); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_2)); db.components().insertPublicPortfolio(); ComponentDto directory = newDirectory(project.getMainBranchComponent(), "dir"); ComponentDto file = newFileDto(directory); db.components().insertComponents(directory, file); SearchWsResponse response = call(SearchRequest.builder().setQualifiers(singletonList("TRK")).build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1, PROJECT_KEY_2); } @Test public void search_views() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_1)); db.components().insertPublicPortfolio(p -> p.setKey("view1")); SearchWsResponse response = call(SearchRequest.builder().setQualifiers(singletonList("VW")).build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly("view1"); } @Test public void search_projects_and_views() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_1)); db.components().insertPublicPortfolio(p -> p.setKey("view1")); SearchWsResponse response = call(SearchRequest.builder().setQualifiers(asList("TRK", "VW")).build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1, "view1"); } @Test public void search_all() { userSession.addPermission(ADMINISTER); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_1)); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_2)); db.components().insertPrivateProject(p -> p.setKey(PROJECT_KEY_3)); SearchWsResponse response = call(SearchRequest.builder().build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1, PROJECT_KEY_2, PROJECT_KEY_3); } @Test public void search_for_old_projects() { userSession.addPermission(ADMINISTER); long aLongTimeAgo = 1_000_000_000L; long inBetween = 2_000_000_000L; long recentTime = 3_000_000_000L; ProjectData oldProject = db.components().insertPublicProject(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(oldProject.getMainBranchDto()).setCreatedAt(aLongTimeAgo)); BranchDto branch = db.components().insertProjectBranch(oldProject.getProjectDto()); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(branch).setCreatedAt(inBetween)); ProjectData recentProject = db.components().insertPublicProject(); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(recentProject.getMainBranchDto()).setCreatedAt(recentTime)); db.commit(); SearchWsResponse result = call(SearchRequest.builder().setAnalyzedBefore(toStringAtUTC(new Date(recentTime + 1_000))).build()); assertThat(result.getComponentsList()).extracting(Component::getKey, Component::getLastAnalysisDate) .containsExactlyInAnyOrder(tuple(oldProject.getProjectDto().getKey(), formatDateTime(inBetween)), tuple(recentProject.projectKey(), formatDateTime(recentTime))); result = call(SearchRequest.builder().setAnalyzedBefore(toStringAtUTC(new Date(recentTime))).build()); assertThat(result.getComponentsList()).extracting(Component::getKey, Component::getLastAnalysisDate) .containsExactlyInAnyOrder(tuple(oldProject.getProjectDto().getKey(), formatDateTime(inBetween))); result = call(SearchRequest.builder().setAnalyzedBefore(toStringAtUTC(new Date(aLongTimeAgo + 1_000L))).build()); assertThat(result.getComponentsList()).isEmpty(); } private static String toStringAtUTC(Date d) { OffsetDateTime offsetTime = d.toInstant().atOffset(ZoneOffset.UTC); return DateUtils.formatDateTime(offsetTime); } @Test public void does_not_return_branches_when_searching_by_key() { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.components().insertProjectBranch(project); userSession.addPermission(ADMINISTER); SearchWsResponse response = call(SearchRequest.builder().build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(project.getKey()); } @Test public void result_is_paginated() { userSession.addPermission(ADMINISTER); for (int i = 1; i <= 9; i++) { int j = i; db.components().insertPrivateProject("project-uuid-" + i, p -> p.setKey("project-key-" + j).setName("Project Name " + j)); } SearchWsResponse response = call(SearchRequest.builder().setPage(2).setPageSize(3).build()); assertThat(response.getComponentsList()).extracting(Component::getKey).containsExactly("project-key-4", "project-key-5", "project-key-6"); } @Test public void provisioned_projects() { userSession.addPermission(ADMINISTER); ProjectDto provisionedProject = db.components().insertPrivateProject().getProjectDto(); ProjectData analyzedProject = db.components().insertPrivateProject(); db.components().insertSnapshot(newAnalysis(analyzedProject.getMainBranchDto())); SearchWsResponse response = call(SearchRequest.builder().setOnProvisionedOnly(true).build()); assertThat(response.getComponentsList()).extracting(Component::getKey) .containsExactlyInAnyOrder(provisionedProject.getKey()) .doesNotContain(analyzedProject.projectKey()); } @Test public void search_by_component_keys() { userSession.addPermission(ADMINISTER); ProjectDto jdk = db.components().insertPrivateProject().getProjectDto(); ProjectDto sonarqube = db.components().insertPrivateProject().getProjectDto(); ProjectDto sonarlint = db.components().insertPrivateProject().getProjectDto(); SearchWsResponse result = call(SearchRequest.builder() .setProjects(Arrays.asList(jdk.getKey(), sonarqube.getKey())) .build()); assertThat(result.getComponentsList()).extracting(Component::getKey) .containsExactlyInAnyOrder(jdk.getKey(), sonarqube.getKey()) .doesNotContain(sonarlint.getKey()); } @Test public void request_throws_IAE_if_more_than_1000_projects() { SearchRequest request = SearchRequest.builder() .setProjects(Collections.nCopies(1_001, "foo")) .build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'projects' can contains only 1000 values, got 1001"); } @Test public void fail_when_not_system_admin() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); SearchRequest request = SearchRequest.builder().build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_on_invalid_qualifier() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); SearchRequest request = SearchRequest.builder().setQualifiers(singletonList("BRC")).build(); assertThatThrownBy(() -> call(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of parameter 'qualifiers' (BRC) must be one of: [TRK, VW, APP]"); } @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action.key()).isEqualTo("search"); assertThat(action.isPost()).isFalse(); assertThat(action.description()).isEqualTo("Search for projects or views to administrate them.<br>Requires 'Administer System' permission"); assertThat(action.isInternal()).isFalse(); assertThat(action.since()).isEqualTo("6.3"); assertThat(action.handler()).isEqualTo(ws.getDef().handler()); assertThat(action.params()).extracting(Param::key) .containsExactlyInAnyOrder("q", "qualifiers", "p", "ps", "visibility", "analyzedBefore", "onProvisionedOnly", "projects"); assertThat(action.responseExample()).isEqualTo(getClass().getResource("search-example.json")); Param qParam = action.param("q"); assertThat(qParam.isRequired()).isFalse(); assertThat(qParam.description()).isEqualTo("Limit search to: " + "<ul>" + "<li>component names that contain the supplied string</li>" + "<li>component keys that contain the supplied string</li>" + "</ul>"); Param qualifierParam = action.param("qualifiers"); assertThat(qualifierParam.isRequired()).isFalse(); assertThat(qualifierParam.description()).isEqualTo("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers"); assertThat(qualifierParam.possibleValues()).containsOnly("TRK", "VW", "APP"); assertThat(qualifierParam.defaultValue()).isEqualTo("TRK"); Param pParam = action.param("p"); assertThat(pParam.isRequired()).isFalse(); assertThat(pParam.defaultValue()).isEqualTo("1"); assertThat(pParam.description()).isEqualTo("1-based page number"); Param psParam = action.param("ps"); assertThat(psParam.isRequired()).isFalse(); assertThat(psParam.defaultValue()).isEqualTo("100"); assertThat(psParam.description()).isEqualTo("Page size. Must be greater than 0 and less or equal than 500"); Param visibilityParam = action.param("visibility"); assertThat(visibilityParam.isRequired()).isFalse(); assertThat(visibilityParam.description()).isEqualTo("Filter the projects that should be visible to everyone (public), or only specific user/groups (private).<br/>" + "If no visibility is specified, the default project visibility will be used."); Param lastAnalysisBefore = action.param("analyzedBefore"); assertThat(lastAnalysisBefore.isRequired()).isFalse(); assertThat(lastAnalysisBefore.since()).isEqualTo("6.6"); Param onProvisionedOnly = action.param("onProvisionedOnly"); assertThat(onProvisionedOnly.possibleValues()).containsExactlyInAnyOrder("true", "false", "yes", "no"); assertThat(onProvisionedOnly.defaultValue()).isEqualTo("false"); assertThat(onProvisionedOnly.since()).isEqualTo("6.6"); } @Test public void json_example() { userSession.addPermission(ADMINISTER); ProjectData publicProject = db.components().insertPublicProject("project-uuid-1", p -> p.setName("Project Name 1").setKey("project-key-1").setPrivate(false)); ProjectData privateProject = db.components().insertPrivateProject("project-uuid-2", p -> p.setName("Project Name 1").setKey("project-key-2")); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(publicProject.getMainBranchDto()) .setCreatedAt(parseDateTime("2017-03-01T11:39:03+0300").getTime()) .setRevision("cfb82f55c6ef32e61828c4cb3db2da12795fd767")); db.getDbClient().snapshotDao().insert(db.getSession(), newAnalysis(privateProject.getMainBranchDto()) .setCreatedAt(parseDateTime("2017-03-02T15:21:47+0300").getTime()) .setRevision("7be96a94ac0c95a61ee6ee0ef9c6f808d386a355")); db.commit(); String response = ws.newRequest() .setMediaType(MediaTypes.JSON) .execute().getInput(); assertJson(response).isSimilarTo(ws.getDef().responseExampleAsString()); assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(response); } private SearchWsResponse call(SearchRequest wsRequest) { TestRequest request = ws.newRequest(); List<String> qualifiers = wsRequest.getQualifiers(); if (!qualifiers.isEmpty()) { request.setParam(ComponentsWsParameters.PARAM_QUALIFIERS, Joiner.on(",").join(qualifiers)); } ofNullable(wsRequest.getQuery()).ifPresent(query -> request.setParam(TEXT_QUERY, query)); ofNullable(wsRequest.getPage()).ifPresent(page -> request.setParam(PAGE, String.valueOf(page))); ofNullable(wsRequest.getPageSize()).ifPresent(pageSize -> request.setParam(PAGE_SIZE, String.valueOf(pageSize))); ofNullable(wsRequest.getVisibility()).ifPresent(v -> request.setParam(PARAM_VISIBILITY, v)); ofNullable(wsRequest.getAnalyzedBefore()).ifPresent(d -> request.setParam(PARAM_ANALYZED_BEFORE, d)); ofNullable(wsRequest.getProjects()).ifPresent(l1 -> request.setParam(PARAM_PROJECTS, String.join(",", l1))); request.setParam(PARAM_ON_PROVISIONED_ONLY, String.valueOf(wsRequest.isOnProvisionedOnly())); return request.executeProtobuf(SearchWsResponse.class); } }
18,169
46.441253
169
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/SearchMyProjectsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.Metric.Level; import org.sonar.api.measures.Metric.ValueType; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Projects.SearchMyProjectsWsResponse; import org.sonarqube.ws.Projects.SearchMyProjectsWsResponse.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.db.user.UserTesting.newUserDto; import static org.sonar.test.JsonAssert.assertJson; public class SearchMyProjectsActionIT { @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public final DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private WsActionTester ws; private UserDto user; private MetricDto alertStatusMetric; @Before public void setUp() { user = db.users().insertUser(); userSession.logIn(user); alertStatusMetric = dbClient.metricDao().insert(dbSession, newMetricDto().setKey(ALERT_STATUS_KEY).setValueType(ValueType.LEVEL.name())); db.commit(); ws = new WsActionTester(new SearchMyProjectsAction(dbClient, userSession)); } @Test public void search_json_example() { ProjectData jdk7 = insertJdk7(); ProjectData cLang = insertClang(); db.projectLinks().insertProvidedLink(jdk7.getProjectDto(), l -> l.setHref("http://www.oracle.com").setType(ProjectLinkDto.TYPE_HOME_PAGE).setName("Home")); db.projectLinks().insertProvidedLink(jdk7.getProjectDto(), l -> l.setHref("http://download.java.net/openjdk/jdk8/").setType(ProjectLinkDto.TYPE_SOURCES).setName("Sources")); long oneTime = DateUtils.parseDateTime("2016-06-10T13:17:53+0000").getTime(); long anotherTime = DateUtils.parseDateTime("2016-06-11T14:25:53+0000").getTime(); SnapshotDto jdk7Snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(jdk7.getMainBranchDto()).setCreatedAt(oneTime)); SnapshotDto cLangSnapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(cLang.getMainBranchDto()).setCreatedAt(anotherTime)); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(jdk7.getMainBranchDto(), alertStatusMetric).setData(Level.ERROR.name())); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(cLang.getMainBranchDto(), alertStatusMetric).setData(Level.OK.name())); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, cLang.getProjectDto()); db.commit(); System.setProperty("user.timezone", "UTC"); String result = ws.newRequest().execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("search_my_projects-example.json")); } @Test public void return_only_current_user_projects() { ProjectData jdk7 = insertJdk7(); ProjectData cLang = insertClang(); UserDto anotherUser = db.users().insertUser(newUserDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertProjectPermissionOnUser(anotherUser, UserRole.ADMIN, cLang.getProjectDto()); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isOne(); } @Test public void return_only_first_1000_projects() { IntStream.range(0, 1_010).forEach(i -> { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project); }); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getPaging().getTotal()).isEqualTo(1_000); } @Test public void sort_projects_by_name() { ComponentDto b_project = db.components().insertPrivateProject(p -> p.setName("B_project_name")).getMainBranchComponent(); ComponentDto c_project = db.components().insertPrivateProject(p -> p.setName("c_project_name")).getMainBranchComponent(); ComponentDto a_project = db.components().insertPrivateProject(p -> p.setName("A_project_name")).getMainBranchComponent(); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, b_project); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, a_project); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, c_project); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isEqualTo(3); } @Test public void paginate_projects() { for (int i = 0; i < 10; i++) { int j = i; ProjectData project = db.components().insertPrivateProject(p -> p.setName("project-" + j)); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project.getProjectDto()); } SearchMyProjectsWsResponse result = ws.newRequest() .setParam(Param.PAGE, "2") .setParam(Param.PAGE_SIZE, "3") .executeProtobuf(SearchMyProjectsWsResponse.class); assertThat(result.getProjectsList()).extracting(Project::getName).containsExactly("project-3", "project-4", "project-5"); assertThat(result.getProjectsCount()).isEqualTo(3); } @Test public void return_only_projects_when_user_is_admin() { ProjectData jdk7 = insertJdk7(); ProjectData clang = insertClang(); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, clang.getProjectDto()); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isOne(); } @Test public void does_not_return_views() { ProjectData jdk7 = insertJdk7(); PortfolioDto portfolio = insertPortfolio(); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, portfolio); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isOne(); } @Test public void does_not_return_branches() { ProjectData project = db.components().insertPublicProject(); BranchDto branch = db.components().insertProjectBranch(project.getProjectDto()); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project.getProjectDto()); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsList()) .extracting(Project::getKey) .containsExactlyInAnyOrder(project.getProjectDto().getKey()); } @Test public void admin_via_groups() { ProjectData jdk7 = insertJdk7(); ProjectData cLang = insertClang(); GroupDto group = db.users().insertGroup(); db.users().insertMember(group, user); db.users().insertEntityPermissionOnGroup(group, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertEntityPermissionOnGroup(group, UserRole.USER, cLang.getProjectDto()); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isOne(); } @Test public void admin_via_groups_and_users() { ProjectData jdk7 = insertJdk7(); ProjectData cLang = insertClang(); ProjectData sonarqube = db.components().insertPrivateProject(); GroupDto group = db.users().insertGroup(); db.users().insertMember(group, user); db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7.getProjectDto()); db.users().insertEntityPermissionOnGroup(group, UserRole.ADMIN, cLang.getProjectDto()); // admin via group and user db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, sonarqube.getProjectDto()); db.users().insertEntityPermissionOnGroup(group, UserRole.ADMIN, sonarqube.getProjectDto()); SearchMyProjectsWsResponse result = callWs(); assertThat(result.getProjectsCount()).isEqualTo(3); } @Test public void empty_response() { String result = ws.newRequest().execute().getInput(); assertJson(result).isSimilarTo("{\"projects\":[]}"); } @Test public void fail_if_not_authenticated() { userSession.anonymous(); assertThatThrownBy(this::callWs) .isInstanceOf(UnauthorizedException.class); } private ProjectData insertClang() { return db.components().insertPrivateProject(Uuids.UUID_EXAMPLE_01, p -> p .setName("Clang") .setKey("clang")); } private ProjectData insertJdk7() { return db.components().insertPrivateProject(Uuids.UUID_EXAMPLE_02, p -> p .setName("JDK 7") .setKey("net.java.openjdk:jdk7") .setDescription("JDK")); } private PortfolioDto insertPortfolio() { String uuid = "752d8bfd-420c-4a83-a4e5-8ab19b13c8fc"; return db.components().insertPublicPortfolioDto(p -> p.setUuid("752d8bfd-420c-4a83-a4e5-8ab19b13c8fc") .setName("Java") .setKey("Java"), p -> p.setRootUuid(uuid)); } private SearchMyProjectsWsResponse callWs() { return ws.newRequest() .executeProtobuf(SearchMyProjectsWsResponse.class); } }
10,976
38.485612
177
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/SearchMyScannableProjectsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.project.ProjectDto; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.web.UserRole.SCAN; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.Projects.SearchMyScannableProjectsResponse; import static org.sonarqube.ws.Projects.SearchMyScannableProjectsResponse.Project; public class SearchMyScannableProjectsActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final WsActionTester ws = new WsActionTester( new SearchMyScannableProjectsAction(db.getDbClient(), new ProjectFinder(db.getDbClient(), userSession))); @Test public void projects_filtered_by_query() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Project Three")).getProjectDto(); ProjectDto project4 = db.components().insertPublicProject(p -> p.setKey("project:four").setName("Project Four")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); List<Project> result = ws.newRequest() .setParam(TEXT_QUERY, "project") .executeProtobuf(SearchMyScannableProjectsResponse.class) .getProjectsList(); assertThat(result) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple("project:three", "Project Three"), tuple("project:four", "Project Four")); } @Test public void projects_not_filtered_by_empty_query() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Project Three")).getProjectDto(); ProjectDto project4 = db.components().insertPublicProject(p -> p.setKey("project:four").setName("Project Four")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); List<Project> result = ws.newRequest() .setParam(TEXT_QUERY, "") .executeProtobuf(SearchMyScannableProjectsResponse.class) .getProjectsList(); assertThat(result) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple("project:one", "Projet Un"), tuple("project:two", "Projet Deux"), tuple("project:three", "Project Three"), tuple("project:four", "Project Four")); } @Test public void projects_filtered_by_scan_permission() { db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Project Three")).getProjectDto(); db.components().insertPublicProject(p -> p.setKey("project:four").setName("Project Four")).getProjectDto(); List<Project> result = ws.newRequest() .executeProtobuf(SearchMyScannableProjectsResponse.class) .getProjectsList(); assertThat(result).isEmpty(); } @Test public void projects_filtered_for_anonymous_user() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); ProjectDto project3 = db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Project Three")).getProjectDto(); ProjectDto project4 = db.components().insertPublicProject(p -> p.setKey("project:four").setName("Project Four")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2, project3, project4); WsActionTester ws = new WsActionTester( new SearchMyScannableProjectsAction(db.getDbClient(), new ProjectFinder(db.getDbClient(), userSession.anonymous()))); List<Project> result = ws.newRequest() .executeProtobuf(SearchMyScannableProjectsResponse.class) .getProjectsList(); assertThat(result).isEmpty(); } @Test public void projects_not_filtered_due_to_global_scan_permission() { db.components().insertPrivateProject(p -> p.setKey("project:one").setName("Projet Un")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:two").setName("Projet Deux")).getProjectDto(); db.components().insertPrivateProject(p -> p.setKey("project:three").setName("Project Three")).getProjectDto(); db.components().insertPublicProject(p -> p.setKey("project:four").setName("Project Four")).getProjectDto(); userSession.addPermission(GlobalPermission.SCAN); List<Project> result = ws.newRequest() .executeProtobuf(SearchMyScannableProjectsResponse.class) .getProjectsList(); assertThat(result) .extracting(Project::getKey, Project::getName) .containsExactlyInAnyOrder( tuple("project:one", "Projet Un"), tuple("project:two", "Projet Deux"), tuple("project:three", "Project Three"), tuple("project:four", "Project Four")); } @Test public void json_example() { ProjectDto project1 = db.components().insertPrivateProject(p -> p.setKey("project-key-1").setName("Project 1")).getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject(p -> p.setKey("project-key-2").setName("Project 2")).getProjectDto(); ProjectDto project3 = db.components().insertPublicProject(p -> p.setKey("public-project-without-scan-permissions") .setName("Public Project with Scan Permissions")).getProjectDto(); userSession.addProjectPermission(SCAN, project1, project2); userSession.registerProjects(project3); String result = ws.newRequest() .execute().getInput(); assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString()); assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(result); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("search_my_scannable_projects"); assertThat(definition.since()).isEqualTo("9.5"); assertThat(definition.isInternal()).isTrue(); assertThat(definition.isPost()).isFalse(); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.params()) .extracting(Param::key, Param::isRequired) .containsExactlyInAnyOrder( tuple("q", false)); } }
8,326
45.261111
136
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/UpdateDefaultVisibilityActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.server.project.ws.UpdateDefaultVisibilityAction.ACTION; import static org.sonar.server.project.ws.UpdateDefaultVisibilityAction.PARAM_PROJECT_VISIBILITY; public class UpdateDefaultVisibilityActionIT { @Rule public final DbTester dbTester = DbTester.create(); @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); public final ProjectDefaultVisibility projectDefaultVisibility = new ProjectDefaultVisibility(dbTester.getDbClient()); private final UpdateDefaultVisibilityAction underTest = new UpdateDefaultVisibilityAction(userSession, dbTester.getDbClient(), projectDefaultVisibility); private final WsActionTester wsTester = new WsActionTester(underTest); @Test public void change_project_visibility_to_private() { projectDefaultVisibility.set(dbTester.getSession(), Visibility.PUBLIC); dbTester.commit(); userSession.logIn().setSystemAdministrator(); wsTester.newRequest() .setParam(PARAM_PROJECT_VISIBILITY, "private") .execute(); assertThat(projectDefaultVisibility.get(dbTester.getSession())).isEqualTo(Visibility.PRIVATE); } @Test public void change_project_visibility_to_public() { projectDefaultVisibility.set(dbTester.getSession(), Visibility.PRIVATE); dbTester.commit(); userSession.logIn().setSystemAdministrator(); wsTester.newRequest() .setParam(PARAM_PROJECT_VISIBILITY, "public") .execute(); assertThat(projectDefaultVisibility.get(dbTester.getSession())).isEqualTo(Visibility.PUBLIC); } @Test public void fail_if_not_logged_as_system_administrator() { userSession.logIn(); TestRequest request = wsTester.newRequest() .setParam(PARAM_PROJECT_VISIBILITY, "private"); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } @Test public void verify_define() { WebService.Action action = wsTester.getDef(); assertThat(action.key()).isEqualTo(ACTION); assertThat(action.isPost()).isTrue(); assertThat(action.description()).isNotEmpty(); assertThat(action.isInternal()).isTrue(); assertThat(action.since()).isEqualTo("6.4"); assertThat(action.handler()).isEqualTo(underTest); assertThat(action.changelog()) .extracting(Change::getVersion, Change::getDescription) .contains(tuple("7.3", "This WS used to be located at /api/organizations/update_project_visibility")); WebService.Param projectVisibility = action.param(PARAM_PROJECT_VISIBILITY); assertThat(projectVisibility.isRequired()).isTrue(); assertThat(projectVisibility.possibleValues()).containsExactlyInAnyOrder("private", "public"); assertThat(projectVisibility.description()).isEqualTo("Default visibility for projects"); } }
4,278
38.256881
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/UpdateKeyActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.ComponentService; import org.sonar.server.es.Indexers; import org.sonar.server.es.IndexersImpl; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.project.ProjectLifeCycleListenersImpl; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_FROM; import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_TO; public class UpdateKeyActionIT { private static final String ANOTHER_KEY = "another_key"; @Rule public final DbTester db = DbTester.create(System2.INSTANCE); @Rule public final UserSessionRule userSessionRule = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); private final Indexers indexers = new IndexersImpl(); private final ComponentService componentService = new ComponentService(dbClient, userSessionRule, indexers, new ProjectLifeCycleListenersImpl()); private final ComponentFinder componentFinder = new ComponentFinder(dbClient, null); private final WsActionTester ws = new WsActionTester(new UpdateKeyAction(dbClient, componentService, componentFinder)); @Test public void update_key_of_project_referenced_by_its_key() { ProjectData project = insertProject(); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); call(project.projectKey(), ANOTHER_KEY); assertThat(selectMainBranchByKey(project.projectKey())).isEmpty(); assertThat(selectMainBranchByKey(ANOTHER_KEY).get().uuid()).isEqualTo(project.getMainBranchComponent().uuid()); assertThat(selectProjectByKey(project.projectKey())).isEmpty(); assertThat(selectProjectByKey(ANOTHER_KEY).get().getUuid()).isEqualTo(project.getProjectDto().getUuid()); } @Test public void fail_if_not_authorized() { ProjectData project = insertProject(); userSessionRule.addProjectPermission(UserRole.USER, project.getProjectDto()); String projectKey = project.projectKey(); assertThatThrownBy(() -> call(projectKey, ANOTHER_KEY)) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void fail_if_new_key_is_not_provided() { ProjectData project = insertProject(); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); String projectKey = project.projectKey(); assertThatThrownBy(() -> call(projectKey, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'to' parameter is missing"); } @Test public void fail_if_key_not_provided() { assertThatThrownBy(() -> call(null, ANOTHER_KEY)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'from' parameter is missing"); } @Test public void fail_if_project_does_not_exist() { assertThatThrownBy(() -> call("UNKNOWN_UUID", ANOTHER_KEY)) .isInstanceOf(NotFoundException.class); } @Test public void api_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.since()).isEqualTo("6.1"); assertThat(definition.isPost()).isTrue(); assertThat(definition.key()).isEqualTo("update_key"); assertThat(definition.changelog()).hasSize(1); assertThat(definition.params()) .hasSize(2) .extracting(Param::key) .containsOnlyOnce("from", "to"); } private ProjectData insertProject() { return db.components().insertPrivateProject(); } private String call(@Nullable String key, @Nullable String newKey) { TestRequest request = ws.newRequest(); if (key != null) { request.setParam(PARAM_FROM, key); } if (newKey != null) { request.setParam(PARAM_TO, newKey); } return request.execute().getInput(); } private Optional<ComponentDto> selectMainBranchByKey(String key) { return db.getDbClient().componentDao().selectByKey(db.getSession(), key); } private Optional<ProjectDto> selectProjectByKey(String key) { return db.getDbClient().projectDao().selectProjectByKey(db.getSession(), key); } }
5,730
36.703947
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/project/ws/UpdateVisibilityActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.project.ws; import java.util.Arrays; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.PortfolioData; import org.sonar.db.component.ProjectData; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.permission.GroupPermissionDto; import org.sonar.db.permission.UserPermissionDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.Indexers; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.UnauthorizedException; import org.sonar.server.permission.PermissionService; import org.sonar.server.permission.PermissionServiceImpl; import org.sonar.server.permission.index.FooIndexDefinition; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static java.util.Arrays.stream; import static java.util.Optional.of; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY; import static org.sonar.db.component.ComponentTesting.newProjectCopy; public class UpdateVisibilityActionIT { private static final String PARAM_VISIBILITY = "visibility"; private static final String PARAM_PROJECT = "project"; private static final String PUBLIC = "public"; private static final String PRIVATE = "private"; private static final Set<String> GLOBAL_PERMISSIONS_NAME_SET = stream(GlobalPermission.values()).map(GlobalPermission::getKey) .collect(Collectors.toSet()); @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public final EsTester es = EsTester.createCustom(new FooIndexDefinition()); @Rule public final UserSessionRule userSessionRule = UserSessionRule.standalone().logIn(); private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT); private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes); private final Set<String> PROJECT_PERMISSIONS_BUT_USER_AND_CODEVIEWER = permissionService.getAllProjectPermissions().stream() .filter(perm -> !perm.equals(UserRole.USER) && !perm.equals(UserRole.CODEVIEWER)) .collect(Collectors.toSet()); private final DbClient dbClient = dbTester.getDbClient(); private final DbSession dbSession = dbTester.getSession(); private final TestIndexers projectIndexers = new TestIndexers(); private final Configuration configuration = mock(Configuration.class); private final UpdateVisibilityAction underTest = new UpdateVisibilityAction(dbClient, userSessionRule, projectIndexers, new SequenceUuidFactory(), configuration); private final WsActionTester ws = new WsActionTester(underTest); private final Random random = new Random(); private final String randomVisibility = random.nextBoolean() ? PUBLIC : PRIVATE; private final TestRequest request = ws.newRequest(); @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("update_visibility"); assertThat(definition.isPost()).isTrue(); assertThat(definition.since()).isEqualTo("6.4"); assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("project", "visibility"); } @Test public void execute_fails_if_user_is_not_logged_in() { userSessionRule.anonymous(); assertThatThrownBy(request::execute) .isInstanceOf(UnauthorizedException.class) .hasMessage("Authentication is required"); } @Test public void execute_fails_with_IAE_when_project_parameter_is_not_provided() { assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'project' parameter is missing"); } @Test public void execute_fails_with_IAE_when_project_parameter_is_not_empty() { assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'project' parameter is missing"); } @Test public void execute_fails_with_IAE_when_parameter_visibility_is_not_provided() { request.setParam(PARAM_PROJECT, "foo"); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'visibility' parameter is missing"); } @Test public void execute_fails_with_IAE_when_parameter_visibility_is_empty() { request.setParam(PARAM_PROJECT, "foo") .setParam(PARAM_VISIBILITY, ""); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Value of parameter '" + PARAM_VISIBILITY + "' () must be one of: [private, public]"); } @Test public void execute_fails_with_IAE_when_value_of_parameter_visibility_is_not_lowercase() { request.setParam(PARAM_PROJECT, "foo"); Stream.of("PUBLIC", "pUBliC", "PRIVATE", "PrIVAtE") .forEach(visibility -> { try { request.setParam(PARAM_VISIBILITY, visibility).execute(); fail("An exception should have been raised"); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(format("Value of parameter '%s' (%s) must be one of: [private, public]", PARAM_VISIBILITY, visibility)); } }); } @Test public void execute_fails_with_NotFoundException_when_specified_component_does_not_exist() { request.setParam(PARAM_PROJECT, "foo") .setParam(PARAM_VISIBILITY, randomVisibility); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Component must be a project, a portfolio or an application"); } @Test public void execute_fails_with_BadRequestException_if_specified_component_is_neither_a_project_a_portfolio_nor_an_application() { ProjectData project = randomPublicOrPrivateProject(); ComponentDto dir = ComponentTesting.newDirectory(project.getMainBranchComponent(), "path"); ComponentDto file = ComponentTesting.newFileDto(project.getMainBranchComponent()); dbTester.components().insertComponents(dir, file); ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); PortfolioData portfolio = dbTester.components().insertPrivatePortfolioData(); ComponentDto subView = ComponentTesting.newSubPortfolio(portfolio.getRootComponent()); ComponentDto projectCopy = newProjectCopy("foo", project.getMainBranchComponent(), subView); dbTester.components().insertComponents(subView, projectCopy); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto(), application); userSessionRule.addPortfolioPermission(UserRole.ADMIN, portfolio.getPortfolioDto()); Stream.of(project.getProjectDto(), portfolio.getPortfolioDto(), application).forEach(c -> request .setParam(PARAM_PROJECT, c.getKey()) .setParam(PARAM_VISIBILITY, randomVisibility) .execute()); Stream.of(dir, file, subView, projectCopy) .forEach(nonRootComponent -> { request.setParam(PARAM_PROJECT, nonRootComponent.getKey()) .setParam(PARAM_VISIBILITY, randomVisibility); try { request.execute(); fail("a BadRequestException should have been raised"); } catch (BadRequestException e) { assertThat(e.getMessage()).isEqualTo("Component must be a project, a portfolio or an application"); } }); } @Test public void execute_throws_ForbiddenException_if_user_has_no_permission_on_specified_component() { ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent(); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, randomVisibility); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void execute_throws_ForbiddenException_if_user_has_all_permissions_but_ADMIN_on_specified_component() { ComponentDto project = dbTester.components().insertPublicProject().getMainBranchComponent(); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, randomVisibility); userSessionRule.addProjectPermission(UserRole.ISSUE_ADMIN, project); Arrays.stream(GlobalPermission.values()) .forEach(userSessionRule::addPermission); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void execute_throws_ForbiddenException_if_user_has_ADMIN_permission_but_sonar_allowPermissionManagementForProjectAdmins_is_set_to_false() { when(configuration.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)).thenReturn(of(false)); ComponentDto project = dbTester.components().insertPublicProject().getMainBranchComponent(); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, randomVisibility); userSessionRule.addProjectPermission(UserRole.ADMIN, project); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void execute_throws_ForbiddenException_if_user_has_global_ADMIN_permission_even_if_sonar_allowPermissionManagementForProjectAdmins_is_set_to_false() { when(configuration.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)).thenReturn(of(false)); ProjectDto project = dbTester.components().insertPublicProject().getProjectDto(); userSessionRule.setSystemAdministrator().addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, "private"); request.execute(); assertThat(dbClient.projectDao().selectProjectByKey(dbSession, project.getKey()).get().isPrivate()).isTrue(); } @Test public void execute_throws_BadRequestException_if_specified_component_has_pending_tasks() { ProjectData project = randomPublicOrPrivateProject(); IntStream.range(0, 1 + Math.abs(random.nextInt(5))) .forEach(i -> insertPendingTask(project.getMainBranchDto())); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, randomVisibility); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Component visibility can't be changed as long as it has background task(s) pending or in progress"); } @Test public void execute_throws_BadRequestException_if_main_component_of_specified_component_has_in_progress_tasks() { ProjectData project = randomPublicOrPrivateProject(); IntStream.range(0, 1 + Math.abs(random.nextInt(5))) .forEach(i -> insertInProgressTask(project.getMainBranchDto())); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, randomVisibility); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); assertThatThrownBy(request::execute) .isInstanceOf(BadRequestException.class) .hasMessage("Component visibility can't be changed as long as it has background task(s) pending or in progress"); } @Test public void execute_changes_private_flag_of_specified_project_and_all_children_to_specified_new_visibility() { ProjectData project = randomPublicOrPrivateProject(); boolean initiallyPrivate = project.getProjectDto().isPrivate(); BranchDto branchDto = ComponentTesting.newBranchDto(project.projectUuid(), BranchType.BRANCH); dbClient.branchDao().insert(dbSession, branchDto); ComponentDto branch = ComponentTesting.newBranchComponent(project.getProjectDto(), branchDto); ComponentDto dir = ComponentTesting.newDirectory(project.getMainBranchComponent(), "path"); ComponentDto file = ComponentTesting.newFileDto(project.getMainBranchComponent()); dbTester.components().insertComponents(branch, dir, file); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, initiallyPrivate ? PUBLIC : PRIVATE) .execute(); assertThat(dbClient.projectDao().selectProjectByKey(dbSession, project.projectKey()).get().isPrivate()).isEqualTo(!initiallyPrivate); assertThat(isPrivateInDb(branch)).isEqualTo(!initiallyPrivate); assertThat(isPrivateInDb(dir)).isEqualTo(!initiallyPrivate); assertThat(isPrivateInDb(file)).isEqualTo(!initiallyPrivate); } @Test public void execute_has_no_effect_if_specified_project_already_has_specified_visibility() { ProjectData project = randomPublicOrPrivateProject(); boolean initiallyPrivate = project.getProjectDto().isPrivate(); BranchDto branchDto = ComponentTesting.newBranchDto(project.getMainBranchComponent()); dbClient.branchDao().insert(dbSession, branchDto); ComponentDto branch = ComponentTesting.newBranchComponent(project.getProjectDto(), branchDto) .setPrivate(initiallyPrivate); ComponentDto dir = ComponentTesting.newDirectory(project.getMainBranchComponent(), "path") // child is inconsistent with root (should not occur) and won't be fixed .setPrivate(!initiallyPrivate); ComponentDto file = ComponentTesting.newFileDto(project.getMainBranchComponent()) .setPrivate(initiallyPrivate); dbTester.components().insertComponents(branch, dir, file); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, initiallyPrivate ? PRIVATE : PUBLIC) .execute(); assertThat(isPrivateInDb(project.getMainBranchComponent())).isEqualTo(initiallyPrivate); assertThat(isPrivateInDb(branch)).isEqualTo(initiallyPrivate); assertThat(isPrivateInDb(dir)).isEqualTo(!initiallyPrivate); assertThat(isPrivateInDb(file)).isEqualTo(initiallyPrivate); } @Test public void execute_deletes_all_permissions_to_Anyone_on_specified_project_when_new_visibility_is_private() { ProjectDto project = dbTester.components().insertPublicProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); GroupDto group = dbTester.users().insertGroup(); unsafeGiveAllPermissionsToRootComponent(project, user, group); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); verifyHasAllPermissionsButProjectPermissionsToGroupAnyOne(project.getUuid(), user, group); } @Test public void execute_does_not_delete_all_permissions_to_AnyOne_on_specified_project_if_already_private() { ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); GroupDto group = dbTester.users().insertGroup(); unsafeGiveAllPermissionsToRootComponent(project, user, group); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); verifyStillHasAllPermissions(project.getUuid(), user, group); } @Test public void execute_deletes_all_permissions_USER_and_BROWSE_of_specified_project_when_new_visibility_is_public() { ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); GroupDto group = dbTester.users().insertGroup(); unsafeGiveAllPermissionsToRootComponent(project, user, group); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PUBLIC) .execute(); verifyHasAllPermissionsButProjectPermissionsUserAndBrowse(project.getUuid(), user, group); } @Test public void execute_does_not_delete_permissions_USER_and_BROWSE_of_specified_project_when_new_component_is_already_public() { ProjectDto project = dbTester.components().insertPublicProject().getProjectDto(); UserDto user = dbTester.users().insertUser(); GroupDto group = dbTester.users().insertGroup(); unsafeGiveAllPermissionsToRootComponent(project, user, group); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PUBLIC) .execute(); verifyStillHasAllPermissions(project.getUuid(), user, group); } @Test public void execute_updates_permission_of_specified_project_in_indexes_when_changing_visibility() { ProjectData project = randomPublicOrPrivateProject(); boolean initiallyPrivate = project.getProjectDto().isPrivate(); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, initiallyPrivate ? PUBLIC : PRIVATE) .execute(); assertThat(projectIndexers.hasBeenCalledForEntity(project.projectUuid(), Indexers.EntityEvent.PERMISSION_CHANGE)).isTrue(); } @Test public void execute_does_not_update_permission_of_specified_project_in_indexes_if_already_has_specified_visibility() { ProjectData project = randomPublicOrPrivateProject(); boolean initiallyPrivate = project.getProjectDto().isPrivate(); userSessionRule.addProjectPermission(UserRole.ADMIN, project.getProjectDto()); request.setParam(PARAM_PROJECT, project.projectKey()) .setParam(PARAM_VISIBILITY, initiallyPrivate ? PRIVATE : PUBLIC) .execute(); assertThat(projectIndexers.hasBeenCalledForEntity(project.projectUuid())).isFalse(); } @Test public void execute_grants_USER_and_CODEVIEWER_permissions_to_any_user_with_at_least_one_permission_when_making_project_private() { ProjectDto project = dbTester.components().insertPublicProject().getProjectDto(); UserDto user1 = dbTester.users().insertUser(); UserDto user2 = dbTester.users().insertUser(); UserDto user3 = dbTester.users().insertUser(); dbTester.users().insertProjectPermissionOnUser(user1, "p1", project); dbTester.users().insertProjectPermissionOnUser(user1, "p2", project); dbTester.users().insertProjectPermissionOnUser(user2, "p2", project); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user1.getUuid(), project.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, "p1", "p2"); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user2.getUuid(), project.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, "p2"); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user3.getUuid(), project.getUuid())) .isEmpty(); } @Test public void execute_grants_USER_and_CODEVIEWER_permissions_to_any_group_with_at_least_one_permission_when_making_project_private() { ProjectDto project = dbTester.components().insertPublicProject().getProjectDto(); GroupDto group1 = dbTester.users().insertGroup(); GroupDto group2 = dbTester.users().insertGroup(); GroupDto group3 = dbTester.users().insertGroup(); dbTester.users().insertEntityPermissionOnGroup(group1, "p1", project); dbTester.users().insertEntityPermissionOnGroup(group1, "p2", project); dbTester.users().insertEntityPermissionOnGroup(group2, "p2", project); userSessionRule.addProjectPermission(UserRole.ADMIN, project); request.setParam(PARAM_PROJECT, project.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group1.getUuid(), project.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, "p1", "p2"); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group2.getUuid(), project.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, "p2"); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group3.getUuid(), project.getUuid())) .isEmpty(); } @Test public void update_a_portfolio_to_private() { PortfolioDto portfolio = dbTester.components().insertPublicPortfolioDto(); GroupDto group = dbTester.users().insertGroup(); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.ISSUE_ADMIN, portfolio); UserDto user = dbTester.users().insertUser(); dbTester.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, portfolio); userSessionRule.addPortfolioPermission(UserRole.ADMIN, portfolio); request.setParam(PARAM_PROJECT, portfolio.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); assertThat(dbClient.portfolioDao().selectByUuid(dbSession, portfolio.getUuid()).get().isPrivate()).isTrue(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), portfolio.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), portfolio.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, UserRole.ADMIN); } @Test public void update_a_portfolio_to_public() { PortfolioDto portfolio = dbTester.components().insertPrivatePortfolioDto(); userSessionRule.addPortfolioPermission(UserRole.ADMIN, portfolio); GroupDto group = dbTester.users().insertGroup(); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.ISSUE_ADMIN, portfolio); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.USER, portfolio); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.CODEVIEWER, portfolio); UserDto user = dbTester.users().insertUser(); dbTester.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, portfolio); dbTester.users().insertProjectPermissionOnUser(user, UserRole.USER, portfolio); dbTester.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, portfolio); request.setParam(PARAM_PROJECT, portfolio.getKey()) .setParam(PARAM_VISIBILITY, PUBLIC) .execute(); assertThat(dbClient.componentDao().selectByUuid(dbSession, portfolio.getUuid()).get().isPrivate()).isFalse(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), portfolio.getUuid())) .containsOnly(UserRole.ISSUE_ADMIN); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), portfolio.getUuid())) .containsOnly(UserRole.ADMIN); } @Test public void update_an_application_to_private() { ProjectDto application = dbTester.components().insertPublicApplication().getProjectDto(); GroupDto group = dbTester.users().insertGroup(); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.ISSUE_ADMIN, application); UserDto user = dbTester.users().insertUser(); dbTester.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, application); userSessionRule.addProjectPermission(UserRole.ADMIN, application); request.setParam(PARAM_PROJECT, application.getKey()) .setParam(PARAM_VISIBILITY, PRIVATE) .execute(); assertThat(dbClient.projectDao().selectByUuid(dbSession, application.getUuid()).get().isPrivate()).isTrue(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), application.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, UserRole.ISSUE_ADMIN); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), application.getUuid())) .containsOnly(UserRole.USER, UserRole.CODEVIEWER, UserRole.ADMIN); } @Test public void update_an_application_to_public() { ProjectDto application = dbTester.components().insertPrivateApplication().getProjectDto(); userSessionRule.addProjectPermission(UserRole.ADMIN, application); GroupDto group = dbTester.users().insertGroup(); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.ISSUE_ADMIN, application); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.USER, application); dbTester.users().insertEntityPermissionOnGroup(group, UserRole.CODEVIEWER, application); UserDto user = dbTester.users().insertUser(); dbTester.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, application); dbTester.users().insertProjectPermissionOnUser(user, UserRole.USER, application); dbTester.users().insertProjectPermissionOnUser(user, UserRole.CODEVIEWER, application); request.setParam(PARAM_PROJECT, application.getKey()) .setParam(PARAM_VISIBILITY, PUBLIC) .execute(); assertThat(dbClient.projectDao().selectApplicationByKey(dbSession, application.getKey()).get().isPrivate()).isFalse(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), application.getUuid())) .containsOnly(UserRole.ISSUE_ADMIN); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), application.getUuid())) .containsOnly(UserRole.ADMIN); } private void unsafeGiveAllPermissionsToRootComponent(ProjectDto projectDto, UserDto user, GroupDto group) { Arrays.stream(GlobalPermission.values()) .forEach(globalPermission -> { dbTester.users().insertPermissionOnAnyone(globalPermission); dbTester.users().insertPermissionOnGroup(group, globalPermission); dbTester.users().insertGlobalPermissionOnUser(user, globalPermission); }); permissionService.getAllProjectPermissions() .forEach(permission -> { unsafeInsertProjectPermissionOnAnyone(projectDto, permission); unsafeInsertProjectPermissionOnGroup(projectDto, group, permission); unsafeInsertProjectPermissionOnUser(projectDto, user, permission); }); } private void unsafeInsertProjectPermissionOnAnyone(ProjectDto projectDto, String permission) { GroupPermissionDto dto = new GroupPermissionDto() .setUuid(Uuids.createFast()) .setGroupUuid(null) .setRole(permission) .setEntityUuid(projectDto.getUuid()) .setEntityName(projectDto.getName()); dbTester.getDbClient().groupPermissionDao().insert(dbTester.getSession(), dto, projectDto, null); dbTester.commit(); } private void unsafeInsertProjectPermissionOnGroup(ProjectDto projectDto, GroupDto group, String permission) { GroupPermissionDto dto = new GroupPermissionDto() .setUuid(Uuids.createFast()) .setGroupUuid(group.getUuid()) .setGroupName(group.getName()) .setRole(permission) .setEntityUuid(projectDto.getUuid()) .setEntityName(projectDto.getName()); dbTester.getDbClient().groupPermissionDao().insert(dbTester.getSession(), dto, projectDto, null); dbTester.commit(); } private void unsafeInsertProjectPermissionOnUser(ProjectDto component, UserDto user, String permission) { UserPermissionDto dto = new UserPermissionDto(Uuids.create(), permission, user.getUuid(), component.getUuid()); dbTester.getDbClient().userPermissionDao().insert(dbTester.getSession(), dto, component, user, null); dbTester.commit(); } private void verifyHasAllPermissionsButProjectPermissionsToGroupAnyOne(String projectUuid, UserDto user, GroupDto group) { assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null)) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, null, projectUuid)) .isEmpty(); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), projectUuid)) .containsAll(permissionService.getAllProjectPermissions()); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), projectUuid)) .containsAll(permissionService.getAllProjectPermissions()); } private void verifyHasAllPermissionsButProjectPermissionsUserAndBrowse(String projectUuid, UserDto user, GroupDto group) { assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null)) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, null, projectUuid)) .doesNotContain(UserRole.USER) .doesNotContain(UserRole.CODEVIEWER) .containsAll(PROJECT_PERMISSIONS_BUT_USER_AND_CODEVIEWER); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), projectUuid)) .doesNotContain(UserRole.USER) .doesNotContain(UserRole.CODEVIEWER) .containsAll(PROJECT_PERMISSIONS_BUT_USER_AND_CODEVIEWER); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), projectUuid)) .doesNotContain(UserRole.USER) .doesNotContain(UserRole.CODEVIEWER) .containsAll(PROJECT_PERMISSIONS_BUT_USER_AND_CODEVIEWER); } private void verifyStillHasAllPermissions(String projectUuid, UserDto user, GroupDto group) { assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null)) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid())) .containsAll(GLOBAL_PERMISSIONS_NAME_SET); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, null, projectUuid)) .containsAll(permissionService.getAllProjectPermissions()); assertThat(dbClient.groupPermissionDao().selectEntityPermissionsOfGroup(dbSession, group.getUuid(), projectUuid)) .containsAll(permissionService.getAllProjectPermissions()); assertThat(dbClient.userPermissionDao().selectEntityPermissionsOfUser(dbSession, user.getUuid(), projectUuid)) .containsAll(permissionService.getAllProjectPermissions()); } private void insertPendingTask(BranchDto branch) { insertCeQueueDto(branch, CeQueueDto.Status.PENDING); } private void insertInProgressTask(BranchDto branch) { insertCeQueueDto(branch, CeQueueDto.Status.IN_PROGRESS); } private int counter = 0; private void insertCeQueueDto(BranchDto branch, CeQueueDto.Status status) { dbClient.ceQueueDao().insert(dbTester.getSession(), new CeQueueDto() .setUuid("pending" + counter++) .setComponentUuid(branch.getUuid()) .setEntityUuid(branch.getProjectUuid()) .setTaskType("foo") .setStatus(status)); dbTester.commit(); } private boolean isPrivateInDb(ComponentDto component) { return dbClient.componentDao().selectByUuid(dbTester.getSession(), component.uuid()).get().isPrivate(); } private ProjectData randomPublicOrPrivateProject() { return random.nextBoolean() ? dbTester.components().insertPublicProject() : dbTester.components().insertPrivateProject(); } }
34,386
48.194564
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/CreateEventActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectanalysis.ws; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectAnalyses; import org.sonarqube.ws.ProjectAnalyses.CreateEventResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.component.SnapshotTesting.newSnapshot; import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER; import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_CATEGORY; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.WsRequest.Method.POST; public class CreateEventActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private System2 system = mock(System2.class); private WsActionTester ws = new WsActionTester(new CreateEventAction(dbClient, uuidFactory, system, userSession)); @Before public void setUp() { when(system.now()).thenReturn(42L); } @Test public void json_example() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project, s -> s.setUuid("A2")); db.commit(); uuidFactory = mock(UuidFactory.class); when(uuidFactory.create()).thenReturn("E1"); ws = new WsActionTester(new CreateEventAction(dbClient, uuidFactory, system, userSession)); logInAsProjectAdministrator(project); String result = ws.newRequest() .setParam(PARAM_ANALYSIS, analysis.getUuid()) .setParam(PARAM_CATEGORY, OTHER.name()) .setParam(PARAM_NAME, "My Custom Event") .execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("create_event-example.json")); } @Test public void create_event_in_db() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); when(system.now()).thenReturn(123_456_789L); logInAsProjectAdministrator(project); CreateEventResponse result = call(VERSION.name(), "5.6.3", analysis.getUuid()); List<EventDto> dbEvents = dbClient.eventDao().selectByComponentUuid(dbSession, analysis.getRootComponentUuid()); assertThat(dbEvents).hasSize(1); EventDto dbEvent = dbEvents.get(0); assertThat(dbEvent.getName()).isEqualTo("5.6.3"); assertThat(dbEvent.getCategory()).isEqualTo(VERSION.getLabel()); assertThat(dbEvent.getDescription()).isNull(); assertThat(dbEvent.getAnalysisUuid()).isEqualTo(analysis.getUuid()); assertThat(dbEvent.getComponentUuid()).isEqualTo(analysis.getRootComponentUuid()); assertThat(dbEvent.getUuid()).isEqualTo(result.getEvent().getKey()); assertThat(dbEvent.getCreatedAt()).isEqualTo(123_456_789L); assertThat(dbEvent.getDate()).isEqualTo(analysis.getCreatedAt()); } @Test public void create_event_in_branch() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project); SnapshotDto analysis = db.components().insertSnapshot(branch); when(system.now()).thenReturn(123_456_789L); logInAsProjectAdministrator(project); CreateEventResponse result = call(VERSION.name(), "5.6.3", analysis.getUuid()); List<EventDto> dbEvents = dbClient.eventDao().selectByComponentUuid(dbSession, analysis.getRootComponentUuid()); assertThat(dbEvents).hasSize(1); EventDto dbEvent = dbEvents.get(0); assertThat(dbEvent.getName()).isEqualTo("5.6.3"); assertThat(dbEvent.getCategory()).isEqualTo(VERSION.getLabel()); assertThat(dbEvent.getDescription()).isNull(); assertThat(dbEvent.getAnalysisUuid()).isEqualTo(analysis.getUuid()); assertThat(dbEvent.getComponentUuid()).isEqualTo(analysis.getRootComponentUuid()); assertThat(dbEvent.getUuid()).isEqualTo(result.getEvent().getKey()); assertThat(dbEvent.getCreatedAt()).isEqualTo(123_456_789L); assertThat(dbEvent.getDate()).isEqualTo(analysis.getCreatedAt()); } @Test public void create_event_as_project_admin() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); CreateEventResponse result = call(VERSION.name(), "5.6.3", analysis.getUuid()); assertThat(result.getEvent().getKey()).isNotEmpty(); } @Test public void create_version_event() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); call(VERSION.name(), "5.6.3", analysis.getUuid()); Optional<SnapshotDto> newAnalysis = dbClient.snapshotDao().selectByUuid(dbSession, analysis.getUuid()); assertThat(newAnalysis.get().getProjectVersion()).isEqualTo("5.6.3"); } @Test public void create_other_event_with_ws_response() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); CreateEventResponse result = call(OTHER.name(), "Project Import", analysis.getUuid()); SnapshotDto newAnalysis = dbClient.snapshotDao().selectByUuid(dbSession, analysis.getUuid()).get(); assertThat(analysis.getProjectVersion()).isEqualTo(newAnalysis.getProjectVersion()); ProjectAnalyses.Event wsEvent = result.getEvent(); assertThat(wsEvent.getKey()).isNotEmpty(); assertThat(wsEvent.getCategory()).isEqualTo(OTHER.name()); assertThat(wsEvent.getName()).isEqualTo("Project Import"); assertThat(wsEvent.hasDescription()).isFalse(); assertThat(wsEvent.getAnalysis()).isEqualTo(analysis.getUuid()); } @Test public void create_event_without_description() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); CreateEventResponse result = call(OTHER.name(), "Project Import", analysis.getUuid()); ProjectAnalyses.Event event = result.getEvent(); assertThat(event.getKey()).isNotEmpty(); assertThat(event.hasDescription()).isFalse(); } @Test public void create_event_on_application() { ProjectDto application = db.components().insertPrivateApplication().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(application); logInAsProjectAdministrator(application); CreateEventResponse result = call(OTHER.name(), "Application Event", analysis.getUuid()); ProjectAnalyses.Event event = result.getEvent(); assertThat(event.getName()).isEqualTo("Application Event"); } @Test public void create_2_version_events_on_same_project() { ProjectData projectData = db.components().insertPrivateProject(); ProjectDto project = projectData.getProjectDto(); SnapshotDto firstAnalysis = db.components().insertSnapshot(project); SnapshotDto secondAnalysis = db.components().insertSnapshot(project); db.commit(); logInAsProjectAdministrator(project); call(VERSION.name(), "5.6.3", firstAnalysis.getUuid()); call(VERSION.name(), "6.3", secondAnalysis.getUuid()); List<EventDto> events = dbClient.eventDao().selectByComponentUuid(dbSession, projectData.getMainBranchComponent().uuid()); assertThat(events).hasSize(2); } @Test public void fail_if_not_blank_name() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call(OTHER.name(), " ", analysis.getUuid())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_if_analysis_is_not_found() { userSession.logIn(); assertThatThrownBy(() -> call(OTHER.name(), "Project Import", "A42")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Analysis 'A42' not found"); } @Test public void fail_if_2_version_events_on_the_same_analysis() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); call(VERSION.name(), "5.6.3", analysis.getUuid()); assertThatThrownBy(() -> call(VERSION.name(), "6.3", analysis.getUuid())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("A version event already exists on analysis '" + analysis.getUuid() + "'"); } @Test public void fail_if_2_other_events_on_same_analysis_with_same_name() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); call(OTHER.name(), "Project Import", analysis.getUuid()); assertThatThrownBy(() -> call(OTHER.name(), "Project Import", analysis.getUuid())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); } @Test public void fail_if_category_other_than_authorized() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(project); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS, analysis.getUuid()) .setParam(PARAM_NAME, "Project Import") .setParam(PARAM_CATEGORY, "QP") .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_create_version_event_on_application() { ProjectDto application = db.components().insertPrivateApplication().getProjectDto(); SnapshotDto analysis = db.components().insertSnapshot(application); logInAsProjectAdministrator(application); assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("A version event must be created on a project"); } @Test public void fail_if_project_is_not_found() { userSession.logIn(); SnapshotDto analysis = dbClient.snapshotDao().insert(dbSession, newSnapshot().setUuid("A1")); db.commit(); assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Project of analysis 'A1' not found"); } @Test public void throw_ForbiddenException_if_not_project_administrator() { SnapshotDto analysis = db.components().insertProjectAndSnapshot(newPrivateProjectDto("P1")); userSession.logIn(); assertThatThrownBy(() -> call(VERSION.name(), "5.6.3", analysis.getUuid())) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void ws_parameters() { WebService.Action definition = ws.getDef(); assertThat(definition.isPost()).isTrue(); assertThat(definition.key()).isEqualTo("create_event"); assertThat(definition.responseExampleAsString()).isNotEmpty(); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } private CreateEventResponse call(String categoryName, String name, String analysis) { TestRequest httpRequest = ws.newRequest() .setMethod(POST.name()); httpRequest.setParam(PARAM_CATEGORY, categoryName) .setParam(PARAM_NAME, name) .setParam(PARAM_ANALYSIS, analysis); return httpRequest.executeProtobuf(CreateEventResponse.class); } }
14,240
40.640351
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectanalysis.ws; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED; import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS; public class DeleteActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSession)); @Test public void project_administrator_deletes_analysis() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_PROCESSED)); db.components().insertSnapshot(newAnalysis(project).setUuid("A2").setLast(true).setStatus(STATUS_PROCESSED)); logInAsProjectAdministrator(project); call("A1"); db.commit(); assertThat(dbClient.snapshotDao().selectByUuids(dbSession, newArrayList("A1", "A2"))).extracting(SnapshotDto::getUuid, SnapshotDto::getStatus).containsExactly( tuple("A1", STATUS_UNPROCESSED), tuple("A2", STATUS_PROCESSED)); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("delete"); assertThat(definition.isPost()).isTrue(); assertThat(definition.param("analysis").isRequired()).isTrue(); } @Test public void last_analysis_cannot_be_deleted() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(true)); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call("A1")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The last analysis 'A1' cannot be deleted"); } @Test public void fail_when_analysis_is_new_code_period_baseline() { String analysisUuid = RandomStringUtils.randomAlphabetic(12); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project).setUuid(analysisUuid).setLast(false)); db.newCodePeriods().insert(new NewCodePeriodDto() .setProjectUuid(project.uuid()) .setBranchUuid(project.uuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue(analysis.getUuid())); db.commit(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call(analysisUuid)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The analysis '" + analysisUuid + "' can not be deleted because it is set as a new code period baseline"); } @Test public void fail_when_analysis_not_found() { userSession.logIn().setSystemAdministrator(); assertThatThrownBy(() -> call("A42")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Analysis 'A42' not found"); } @Test public void fail_when_analysis_is_unprocessed() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false).setStatus(STATUS_UNPROCESSED)); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call("A1")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Analysis 'A1' not found"); } @Test public void fail_when_not_enough_permission() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setLast(false)); userSession.logIn(); assertThatThrownBy(() -> call("A1")) .isInstanceOf(ForbiddenException.class); } private void call(String analysis) { ws.newRequest() .setParam(PARAM_ANALYSIS, analysis) .execute(); } private void logInAsProjectAdministrator(ComponentDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } }
6,053
39.092715
163
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/DeleteEventActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectanalysis.ws; import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.event.EventTesting.newEvent; import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT; public class DeleteEventActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = db.getDbClient(); private DbSession dbSession = db.getSession(); private WsActionTester ws = new WsActionTester(new DeleteEventAction(db.getDbClient(), userSession)); @Test public void delete_event() { ComponentDto project = ComponentTesting.newPrivateProjectDto(); SnapshotDto analysis = db.components().insertProjectAndSnapshot(project); db.events().insertEvent(newEvent(analysis).setUuid("E1")); db.events().insertEvent(newEvent(analysis).setUuid("E2")); logInAsProjectAdministrator(project); call("E2"); List<EventDto> events = db.getDbClient().eventDao().selectByAnalysisUuid(db.getSession(), analysis.getUuid()); assertThat(events).extracting(EventDto::getUuid).containsExactly("E1"); } @Test public void delete_version_event() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project).setProjectVersion("5.6.3").setLast(false)); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(VERSION.getLabel())); logInAsProjectAdministrator(project); call("E1"); SnapshotDto newAnalysis = dbClient.snapshotDao().selectByUuid(dbSession, analysis.getUuid()).get(); assertThat(newAnalysis.getProjectVersion()).isNull(); } @Test public void fail_if_version_for_last_analysis() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project).setProjectVersion("5.6.3").setLast(true)); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(VERSION.getLabel())); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call("E1")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Cannot delete the version event of last analysis"); } @Test public void fail_if_category_different_than_other_and_version() { ComponentDto project = newPrivateProjectDto("P1"); SnapshotDto analysis = db.components().insertProjectAndSnapshot(project); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory("Profile")); logInAsProjectAdministrator(project); assertThatThrownBy(() -> call("E1")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Event of category 'QUALITY_PROFILE' cannot be modified."); } @Test public void fail_if_event_does_not_exist() { assertThatThrownBy(() -> call("E42")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("E42' not found"); } @Test public void fail_if_not_enough_permission() { SnapshotDto analysis = db.components().insertProjectAndSnapshot(ComponentTesting.newPrivateProjectDto()); db.events().insertEvent(newEvent(analysis).setUuid("E1")); userSession.logIn(); assertThatThrownBy(() -> call("E1")) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_event_not_provided() { assertThatThrownBy(() -> call(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void ws_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("delete_event"); assertThat(definition.isPost()).isTrue(); assertThat(definition.isInternal()).isFalse(); assertThat(definition.param(PARAM_EVENT).isRequired()).isTrue(); } private void call(@Nullable String event) { TestRequest request = ws.newRequest(); if (event != null) { request.setParam(PARAM_EVENT, event); } request.execute(); } private void logInAsProjectAdministrator(ComponentDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } }
6,093
38.064103
122
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectanalysis.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Date; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.web.UserRole; import org.sonar.core.config.CorePropertyDefinitions; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.AnalysisPropertyDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventComponentChangeDto; import org.sonar.db.event.EventComponentChangeDto.ChangeCategory; import org.sonar.db.event.EventDto; import org.sonar.db.event.EventPurgeData; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Common.Paging; import org.sonarqube.ws.ProjectAnalyses.Analysis; import org.sonarqube.ws.ProjectAnalyses.Event; import org.sonarqube.ws.ProjectAnalyses.Project; import org.sonarqube.ws.ProjectAnalyses.SearchResponse; import static java.lang.String.format; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.utils.DateUtils.formatDate; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.event.EventComponentChangeDto.ChangeCategory.ADDED; import static org.sonar.db.event.EventComponentChangeDto.ChangeCategory.FAILED_QUALITY_GATE; import static org.sonar.db.event.EventComponentChangeDto.ChangeCategory.REMOVED; import static org.sonar.db.event.EventDto.CATEGORY_ALERT; import static org.sonar.db.event.EventTesting.newEvent; import static org.sonar.server.projectanalysis.ws.EventCategory.DEFINITION_CHANGE; import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER; import static org.sonar.server.projectanalysis.ws.EventCategory.QUALITY_GATE; import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_BRANCH; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_CATEGORY; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_FROM; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_PROJECT; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_TO; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.WsRequest.Method.POST; @RunWith(DataProviderRunner.class) public class SearchActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = db.getDbClient(); private final WsActionTester ws = new WsActionTester(new SearchAction(dbClient, TestComponentFinder.from(db), userSession)); private final UuidFactoryFast uuidFactoryFast = UuidFactoryFast.getInstance(); @DataProvider public static Object[][] changedBranches() { return new Object[][]{ {null, "newbranch"}, {"newbranch", "anotherbranch"}, {"newbranch", null}, }; } @Test public void json_example() { ProjectData projectData = db.components().insertPrivateProject(c -> c.setKey(KEY_PROJECT_EXAMPLE_001)); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch) .setUuid("A1") .setCreatedAt(parseDateTime("2016-12-11T17:12:45+0100").getTime()) .setProjectVersion("1.2") .setBuildString("1.2.0.322") .setRevision("bfe36592eb7f9f2708b5d358b5b5f33ed535c8cf")); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch) .setUuid("A2") .setCreatedAt(parseDateTime("2016-12-12T17:12:45+0100").getTime()) .setProjectVersion("1.2.1") .setBuildString("1.2.1.423") .setRevision("be6c75b85da526349c44e3978374c95e0b80a96d")); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch) .setUuid("P1") .setCreatedAt(parseDateTime("2015-11-11T10:00:00+0100").getTime()) .setProjectVersion("1.2") .setBuildString("1.2.0.321")); db.getDbClient().analysisPropertiesDao().insert(db.getSession(), new AnalysisPropertyDto() .setUuid("P1-prop-uuid") .setAnalysisUuid(a3.getUuid()) .setKey(CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI) .setValue("Jenkins") .setCreatedAt(1L)); db.newCodePeriods().insert(new NewCodePeriodDto() .setProjectUuid(projectData.getProjectDto().getUuid()) .setBranchUuid(mainBranch.uuid()) .setType(NewCodePeriodType.SPECIFIC_ANALYSIS) .setValue(a1.getUuid())); db.commit(); db.events().insertEvent(newEvent(a1).setUuid("AXt91FkXy_c4CIP4ds6A") .setName("Failed") .setCategory(QUALITY_GATE.getLabel()) .setDescription( "Coverage on New Code < 85, Reliability Rating > 4, Maintainability Rating on New Code > 1, Reliability Rating on New Code > 1, Security Rating on New Code > 1, Duplicated Lines (%) on New Code > 3")); db.events().insertEvent(newEvent(a1).setUuid("AXx_QFJ6Wa8wkfuJ6r5P") .setName("6.3").setCategory(VERSION.getLabel())); db.events().insertEvent(newEvent(a2).setUuid("E21") .setName("Quality Profile changed to Sonar Way") .setCategory(EventCategory.QUALITY_PROFILE.getLabel())); db.events().insertEvent(newEvent(a2).setUuid("E22") .setName("6.3").setCategory(OTHER.getLabel())); EventDto eventDto = db.events().insertEvent(newEvent(a3) .setUuid("E31") .setName("Quality Gate is Red") .setData("{stillFailing: true, status: \"ERROR\"}") .setCategory(CATEGORY_ALERT) .setDescription("")); EventComponentChangeDto changeDto1 = generateEventComponentChange(eventDto, FAILED_QUALITY_GATE, "My project", "app1", "master", mainBranch.uuid()); EventComponentChangeDto changeDto2 = generateEventComponentChange(eventDto, FAILED_QUALITY_GATE, "Another project", "app2", "master", uuidFactoryFast.create()); insertEventComponentChanges(mainBranch, a3, changeDto1, changeDto2); String result = ws.newRequest() .setParam(PARAM_PROJECT, KEY_PROJECT_EXAMPLE_001) .execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("search-example.json")); } private void addProjectPermission(ProjectData projectData) { userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()) .addProjectBranchMapping(projectData.getProjectDto().getUuid(), projectData.getMainBranchComponent()); } @Test public void return_analyses_ordered_by_analysis_date() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A1").setCreatedAt(1_000_000L)); db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A2").setCreatedAt(2_000_000L)); db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A3").setCreatedAt(3_000_000L)); List<Analysis> result = call(mainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(3); assertThat(result).extracting(Analysis::getKey, a -> parseDateTime(a.getDate()).getTime()).containsExactly( tuple("A3", 3_000_000L), tuple("A2", 2_000_000L), tuple("A1", 1_000_000L)); } @Test public void return_only_processed_analyses() { ProjectData projectData = db.components().insertPrivateProject(c -> c.setKey("P1")); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A1")); db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A2").setStatus(SnapshotDto.STATUS_UNPROCESSED)); List<Analysis> result = call("P1").getAnalysesList(); assertThat(result).hasSize(1); assertThat(result.get(0).getKey()).isEqualTo("A1"); } @Test public void return_events() { ProjectData projectData = db.components().insertPrivateProject(c -> c.setKey("P1")); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A1")); SnapshotDto a42 = db.components().insertSnapshot(newAnalysis(ComponentTesting.newPrivateProjectDto()).setUuid("A42")); EventDto e1 = db.events().insertEvent(newEvent(a1).setUuid("E1").setName("N1").setCategory(QUALITY_GATE.getLabel()).setDescription("D1")); EventDto e2 = db.events().insertEvent(newEvent(a1).setUuid("E2").setName("N2").setCategory(VERSION.getLabel()).setDescription("D2")); db.events().insertEvent(newEvent(a42)); List<Analysis> result = call("P1").getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events).hasSize(2); assertThat(events).extracting(Event::getKey, wsToDbCategory(), Event::getName, Event::getDescription).containsOnly( tuple(e1.getUuid(), e1.getCategory(), e1.getName(), e1.getDescription()), tuple(e2.getUuid(), e2.getCategory(), e2.getName(), e2.getDescription())); } @Test public void return_analyses_of_application() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); SnapshotDto secondAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(2_000_000L)); SnapshotDto thirdAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(3_000_000L)); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result) .hasSize(3) .extracting(Analysis::getKey).containsExactly(thirdAnalysis.getUuid(), secondAnalysis.getUuid(), firstAnalysis.getUuid()); assertThat(result.get(0).getEventsList()).isEmpty(); assertThat(result.get(1).getEventsList()).isEmpty(); assertThat(result.get(2).getEventsList()).isEmpty(); } @Test public void return_definition_change_events_on_application_analyses() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto mainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(mainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel())); EventComponentChangeDto changeDto1 = generateEventComponentChange(event, ADDED, "My project", "app1", "master", uuidFactoryFast.create()); EventComponentChangeDto changeDto2 = generateEventComponentChange(event, REMOVED, "Another project", "app2", "master", uuidFactoryFast.create()); insertEventComponentChanges(mainBranch, firstAnalysis, changeDto1, changeDto2); List<Analysis> result = call(mainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", DEFINITION_CHANGE.name(), "E11")); assertThat(events.get(0).getDefinitionChange().getProjectsList()) .extracting(Project::getChangeType, Project::getName, Project::getKey, Project::getNewBranch, Project::getOldBranch) .containsExactly( tuple("ADDED", "My project", "app1", "", ""), tuple("REMOVED", "Another project", "app2", "", "")); } @Test @UseDataProvider("changedBranches") public void application_definition_change_with_branch(@Nullable String oldBranch, @Nullable String newBranch) { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel())); EventComponentChangeDto changeDto1 = generateEventComponentChange(event, REMOVED, "My project", "app1", oldBranch, uuidFactoryFast.create()); EventComponentChangeDto changeDto2 = generateEventComponentChange(event, ADDED, "My project", "app1", newBranch, changeDto1.getComponentUuid()); insertEventComponentChanges(appMainBranch, firstAnalysis, changeDto1, changeDto2); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", DEFINITION_CHANGE.name(), "E11")); assertThat(events.get(0).getDefinitionChange().getProjectsList()) .extracting(Project::getChangeType, Project::getKey, Project::getName, Project::getNewBranch, Project::getOldBranch) .containsExactly(tuple("BRANCH_CHANGED", "app1", "My project", newBranch == null ? "" : newBranch, oldBranch == null ? "" : oldBranch)); } @Test public void incorrect_eventcomponentchange_two_identical_changes_added_on_same_project() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel())); EventComponentChangeDto changeDto1 = generateEventComponentChange(event, ADDED, "My project", "app1", "master", uuidFactoryFast.create()); EventComponentChangeDto changeDto2 = generateEventComponentChange(event, ADDED, "My project", "app1", "master", uuidFactoryFast.create()); EventPurgeData eventPurgeData = new EventPurgeData(appMainBranch.uuid(), firstAnalysis.getUuid()); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto1, eventPurgeData); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto2, eventPurgeData); db.getSession().commit(); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", DEFINITION_CHANGE.name(), "E11")); assertThat(events.get(0).getDefinitionChange().getProjectsList()) .isEmpty(); assertThat(logTester.getLogs(LoggerLevel.ERROR)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly( format("Incorrect changes : [uuid=%s change=ADDED, branch=master] and [uuid=%s, change=ADDED, branch=master]", changeDto1.getUuid(), changeDto2.getUuid())); } @Test public void incorrect_eventcomponentchange_incorrect_category() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel())); EventComponentChangeDto changeDto1 = generateEventComponentChange(event, FAILED_QUALITY_GATE, "My project", "app1", "master", uuidFactoryFast.create()); EventPurgeData eventPurgeData = new EventPurgeData(appMainBranch.uuid(), firstAnalysis.getUuid()); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto1, eventPurgeData); db.getSession().commit(); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", DEFINITION_CHANGE.name(), "E11")); assertThat(events.get(0).getDefinitionChange().getProjectsList()) .isEmpty(); assertThat(logTester.getLogs(LoggerLevel.ERROR)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly("Unknown change FAILED_QUALITY_GATE for eventComponentChange uuid: " + changeDto1.getUuid()); } @Test public void incorrect_eventcomponentchange_three_component_changes_on_same_project() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel())); EventComponentChangeDto changeDto1 = generateEventComponentChange(event, ADDED, "My project", "app1", "master", uuidFactoryFast.create()); EventComponentChangeDto changeDto2 = generateEventComponentChange(event, REMOVED, "Another project", "app1", "", uuidFactoryFast.create()); EventComponentChangeDto changeDto3 = generateEventComponentChange(event, REMOVED, "Another project", "app1", "", uuidFactoryFast.create()); EventPurgeData eventPurgeData = new EventPurgeData(appMainBranch.uuid(), firstAnalysis.getUuid()); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto1, eventPurgeData); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto2, eventPurgeData); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto3, eventPurgeData); db.getSession().commit(); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", DEFINITION_CHANGE.name(), "E11")); assertThat(events.get(0).getDefinitionChange().getProjectsList()) .isEmpty(); assertThat(logTester.getLogs(LoggerLevel.ERROR)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly( format("Too many changes on same project (3) for eventComponentChange uuids : %s,%s,%s", changeDto1.getUuid(), changeDto2.getUuid(), changeDto3.getUuid())); } private void registerApplication(ProjectData appData) { userSession.registerApplication(appData.getProjectDto()) .addProjectBranchMapping(appData.projectUuid(), appData.getMainBranchComponent()); } @Test public void incorrect_quality_gate_information() { ProjectData appData = db.components().insertPublicApplication(); ComponentDto appMainBranch = appData.getMainBranchComponent(); registerApplication(appData); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(appMainBranch).setCreatedAt(1_000_000L)); EventDto event = db.events().insertEvent( newEvent(firstAnalysis) .setName("") .setUuid("E11") .setCategory(CATEGORY_ALERT) .setData("UNPARSEABLE JSON")); // Error in Data EventComponentChangeDto changeDto1 = generateEventComponentChange(event, FAILED_QUALITY_GATE, "My project", "app1", "master", uuidFactoryFast.create()); EventPurgeData eventPurgeData = new EventPurgeData(appMainBranch.uuid(), firstAnalysis.getUuid()); db.getDbClient().eventComponentChangeDao().insert(db.getSession(), changeDto1, eventPurgeData); db.getSession().commit(); List<Analysis> result = call(appMainBranch.getKey()).getAnalysesList(); assertThat(result).hasSize(1); List<Event> events = result.get(0).getEventsList(); assertThat(events) .extracting(Event::getName, Event::getCategory, Event::getKey) .containsExactly(tuple("", QUALITY_GATE.name(), "E11")); // Verify that the values are not populated assertThat(events.get(0).getQualityGate().hasStatus()).isFalse(); assertThat(events.get(0).getQualityGate().hasStillFailing()).isFalse(); assertThat(logTester.getLogs(LoggerLevel.ERROR)) .extracting(LogAndArguments::getFormattedMsg) .containsExactly("Unable to retrieve data from event uuid=E11"); } @Test public void return_analyses_of_portfolio() { ComponentDto view = db.components().insertPublicPortfolio(); userSession.registerPortfolios(view); SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(view).setCreatedAt(1_000_000L)); SnapshotDto secondAnalysis = db.components().insertSnapshot(newAnalysis(view).setCreatedAt(2_000_000L)); SnapshotDto thirdAnalysis = db.components().insertSnapshot(newAnalysis(view).setCreatedAt(3_000_000L)); List<Analysis> result = call(view.getKey()).getAnalysesList(); assertThat(result) .hasSize(3) .extracting(Analysis::getKey).containsExactly(thirdAnalysis.getUuid(), secondAnalysis.getUuid(), firstAnalysis.getUuid()); } @Test public void paginate_analyses() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); IntStream.rangeClosed(1, 9).forEach(i -> db.components().insertSnapshot(newAnalysis(mainBranch).setCreatedAt(1_000_000L * i).setUuid("A" + i))); SearchResponse result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setPage(2) .setPageSize(3) .build()); assertThat(result.getAnalysesList()).extracting(Analysis::getKey) .containsExactly("A6", "A5", "A4"); } @Test public void filter_by_category() { ProjectData projectData = db.components().insertPrivateProject(c -> c.setKey("P1")); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A1")); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A2")); SnapshotDto a42 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A42")); db.events().insertEvent(newEvent(a1).setUuid("E11").setCategory(VERSION.getLabel())); db.events().insertEvent(newEvent(a1).setUuid("E12").setCategory(QUALITY_GATE.getLabel())); db.events().insertEvent(newEvent(a2).setUuid("E21").setCategory(QUALITY_GATE.getLabel())); // Analysis A42 doesn't have a quality gate event db.events().insertEvent(newEvent(a42).setCategory(OTHER.getLabel())); List<Analysis> result = call(SearchRequest.builder() .setProject("P1") .setCategory(QUALITY_GATE) .build()).getAnalysesList(); assertThat(result).extracting(Analysis::getKey).containsOnly("A1", "A2"); } @Test public void paginate_with_filter_on_category() { ProjectData projectData = db.components().insertPrivateProject(c -> c.setKey("P1")); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A1").setCreatedAt(1_000_000L)); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A2").setCreatedAt(2_000_000L)); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A3").setCreatedAt(3_000_000L)); SnapshotDto a42 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("A42")); db.events().insertEvent(newEvent(a1).setUuid("E11").setCategory(VERSION.getLabel())); db.events().insertEvent(newEvent(a1).setUuid("E12").setCategory(QUALITY_GATE.getLabel())); db.events().insertEvent(newEvent(a2).setUuid("E21").setCategory(QUALITY_GATE.getLabel())); db.events().insertEvent(newEvent(a3).setUuid("E31").setCategory(QUALITY_GATE.getLabel())); // Analysis A42 doesn't have a quality gate event db.events().insertEvent(newEvent(a42).setCategory(OTHER.getLabel())); SearchResponse result = call(SearchRequest.builder() .setProject("P1") .setCategory(QUALITY_GATE) .setPage(2) .setPageSize(1) .build()); assertThat(result.getAnalysesList()).extracting(Analysis::getKey).containsOnly("A2"); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal) .containsExactly(2, 1, 3); } @Test public void filter_from_date() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a1").setCreatedAt(1_000_000_000L)); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a2").setCreatedAt(2_000_000_000L)); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a3").setCreatedAt(3_000_000_000L)); SnapshotDto a4 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a4").setCreatedAt(4_000_000_000L)); SearchResponse result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setFrom(formatDateTime(2_000_000_000L)) .build()); assertThat(result.getAnalysesList()) .extracting(Analysis::getKey) .containsOnly(a2.getUuid(), a3.getUuid(), a4.getUuid()) .doesNotContain(a1.getUuid()); } @Test public void filter_to_date() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a1").setCreatedAt(1_000_000_000L)); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a2").setCreatedAt(2_000_000_000L)); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a3").setCreatedAt(3_000_000_000L)); SnapshotDto a4 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a4").setCreatedAt(4_000_000_000L)); SearchResponse result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setTo(formatDateTime(2_000_000_000L)) .build()); assertThat(result.getAnalysesList()) .extracting(Analysis::getKey) .containsOnly(a1.getUuid(), a2.getUuid()) .doesNotContain(a3.getUuid(), a4.getUuid()); } @Test public void filter_by_dates_using_datetime_format() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a1").setCreatedAt(1_000_000_000L)); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a2").setCreatedAt(2_000_000_000L)); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a3").setCreatedAt(3_000_000_000L)); SnapshotDto a4 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a4").setCreatedAt(4_000_000_000L)); SearchResponse result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setFrom(formatDateTime(2_000_000_000L)) .setTo(formatDateTime(3_000_000_000L)) .build()); assertThat(result.getAnalysesList()) .extracting(Analysis::getKey) .containsOnly(a2.getUuid(), a3.getUuid()) .doesNotContain(a1.getUuid(), a4.getUuid()); } @Test public void filter_by_dates_using_date_format() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a1").setCreatedAt(1_000_000_000L)); SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a2").setCreatedAt(2_000_000_000L)); SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a3").setCreatedAt(3_000_000_000L)); SnapshotDto a4 = db.components().insertSnapshot(newAnalysis(mainBranch).setUuid("a4").setCreatedAt(4_000_000_000L)); SearchResponse result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setFrom(formatDate(new Date(2_000_000_000L))) .setTo(formatDate(new Date(3_000_000_000L))) .build()); assertThat(result.getAnalysesList()) .extracting(Analysis::getKey) .containsOnly(a2.getUuid(), a3.getUuid()) .doesNotContain(a1.getUuid(), a4.getUuid()); } @Test public void branch() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey("my_branch")); userSession.addProjectBranchMapping(projectData.projectUuid(), branch); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(branch)); EventDto event = db.events().insertEvent(newEvent(analysis).setCategory(QUALITY_GATE.getLabel())); List<Analysis> result = call(SearchRequest.builder() .setProject(mainBranch.getKey()) .setBranch("my_branch") .build()) .getAnalysesList(); assertThat(result).extracting(Analysis::getKey).containsExactlyInAnyOrder(analysis.getUuid()); assertThat(result.get(0).getEventsList()).extracting(Event::getKey).containsExactlyInAnyOrder(event.getUuid()); } @Test public void empty_response() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SearchResponse result = call(mainBranch.getKey()); assertThat(result.hasPaging()).isTrue(); assertThat(result.getPaging()).extracting(Paging::getPageIndex, Paging::getPageSize, Paging::getTotal).containsExactly(1, 100, 0); assertThat(result.getAnalysesCount()).isZero(); } @Test public void populates_projectVersion_and_buildString() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); SnapshotDto[] analyses = new SnapshotDto[]{ db.components().insertSnapshot(newAnalysis(mainBranch).setProjectVersion(null).setBuildString(null)), db.components().insertSnapshot(newAnalysis(mainBranch).setProjectVersion("a").setBuildString(null)), db.components().insertSnapshot(newAnalysis(mainBranch).setProjectVersion(null).setBuildString("b")), db.components().insertSnapshot(newAnalysis(mainBranch).setProjectVersion("c").setBuildString("d")) }; SearchResponse result = call(mainBranch.getKey()); assertThat(result.getAnalysesList()) .extracting(Analysis::getKey, Analysis::getProjectVersion, Analysis::getBuildString) .containsOnly( tuple(analyses[0].getUuid(), "", ""), tuple(analyses[1].getUuid(), "a", ""), tuple(analyses[2].getUuid(), "", "b"), tuple(analyses[3].getUuid(), "c", "d")); } @Test public void fail_if_not_enough_permissions() { userSession.anonymous(); ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); var projectDbKey = mainBranch.getKey(); assertThatThrownBy(() -> call(projectDbKey)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_enough_permissions_on_applications_projects() { ProjectDto application = db.components().insertPrivateApplication().getProjectDto(); ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); userSession.logIn() .registerApplication(application) .registerProjects(project1, project2) .addProjectPermission(UserRole.USER, application, project1); var projectDbKey = application.getKey(); assertThatThrownBy(() -> call(projectDbKey)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_project_does_not_exist() { assertThatThrownBy(() -> call("P1")) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_not_a_project_portfolio_or_application() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); ComponentDto file = db.components().insertComponent(newFileDto(mainBranch)); db.components().insertSnapshot(newAnalysis(mainBranch)); userSession.registerProjects(projectData.getProjectDto()); var fileDbKey = file.getKey(); assertThatThrownBy(() -> call(fileDbKey)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A project, portfolio or application is required"); } @Test public void fail_if_branch_does_not_exist() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); addProjectPermission(projectData); db.components().insertProjectBranch(mainBranch, b -> b.setKey("my_branch")); var searchRequest = SearchRequest.builder() .setProject(mainBranch.getKey()) .setBranch("another_branch") .build(); assertThatThrownBy(() -> call(searchRequest)) .isInstanceOf(NotFoundException.class) .hasMessage(format("Component '%s' on branch '%s' not found", mainBranch.getKey(), "another_branch")); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("search"); assertThat(definition.since()).isEqualTo("6.3"); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.param("project").isRequired()).isTrue(); assertThat(definition.param("category")).isNotNull(); assertThat(definition.params()).hasSize(8); Param from = definition.param("from"); assertThat(from.since()).isEqualTo("6.5"); Param to = definition.param("to"); assertThat(to.since()).isEqualTo("6.5"); Param branch = definition.param("branch"); assertThat(branch.since()).isEqualTo("6.6"); assertThat(branch.isInternal()).isTrue(); assertThat(branch.isRequired()).isFalse(); } private EventComponentChangeDto generateEventComponentChange(EventDto event, ChangeCategory category, String name, String key, @Nullable String branch, String componentUuid) { return new EventComponentChangeDto() .setCategory(category) .setUuid(uuidFactoryFast.create()) .setComponentName(name) .setComponentKey(key) .setComponentBranchKey(branch) .setComponentUuid(componentUuid) .setEventUuid(event.getUuid()); } private void insertEventComponentChanges(ComponentDto component, SnapshotDto analysis, EventComponentChangeDto... changes) { EventPurgeData eventPurgeData = new EventPurgeData(component.uuid(), analysis.getUuid()); for (EventComponentChangeDto change : changes) { db.getDbClient().eventComponentChangeDao().insert(db.getSession(), change, eventPurgeData); } db.getSession().commit(); } private static Function<Event, String> wsToDbCategory() { return e -> e == null ? null : EventCategory.valueOf(e.getCategory()).getLabel(); } private SearchResponse call(@Nullable String project) { SearchRequest.Builder request = SearchRequest.builder(); ofNullable(project).ifPresent(request::setProject); return call(request.build()); } private SearchResponse call(SearchRequest wsRequest) { TestRequest request = ws.newRequest() .setMethod(POST.name()); ofNullable(wsRequest.getProject()).ifPresent(project -> request.setParam(PARAM_PROJECT, project)); ofNullable(wsRequest.getBranch()).ifPresent(branch1 -> request.setParam(PARAM_BRANCH, branch1)); ofNullable(wsRequest.getCategory()).ifPresent(category -> request.setParam(PARAM_CATEGORY, category.name())); ofNullable(wsRequest.getPage()).ifPresent(page -> request.setParam(Param.PAGE, String.valueOf(page))); ofNullable(wsRequest.getPageSize()).ifPresent(pageSize -> request.setParam(Param.PAGE_SIZE, String.valueOf(pageSize))); ofNullable(wsRequest.getFrom()).ifPresent(from -> request.setParam(PARAM_FROM, from)); ofNullable(wsRequest.getTo()).ifPresent(to -> request.setParam(PARAM_TO, to)); return request.executeProtobuf(SearchResponse.class); } }
39,738
49.049118
209
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectanalysis/ws/UpdateEventActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectanalysis.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectAnalyses; import org.sonarqube.ws.ProjectAnalyses.UpdateEventResponse; import static java.util.Optional.ofNullable; import static org.apache.commons.lang.StringUtils.repeat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.event.EventTesting.newEvent; import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER; import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT; import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.client.WsRequest.Method.POST; public class UpdateEventActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final WsActionTester ws = new WsActionTester(new UpdateEventAction(dbClient, userSession)); @Test public void json_example() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project).setUuid("A2")); db.events().insertEvent(newEvent(analysis) .setUuid("E1") .setCategory(OTHER.getLabel()) .setName("Original Name") .setDescription("Original Description")); logInAsProjectAdministrator(project); String result = ws.newRequest() .setParam(PARAM_EVENT, "E1") .setParam(PARAM_NAME, "My Custom Event") .execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("update_event-example.json")); } @Test public void update_name_in_db() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); EventDto originalEvent = db.events().insertEvent(newEvent(analysis).setUuid("E1").setName("Original Name")); call("E1", "name"); EventDto newEvent = dbClient.eventDao().selectByUuid(dbSession, "E1").get(); assertThat(newEvent.getName()).isEqualTo("name"); assertThat(newEvent.getDescription()).isNull(); assertThat(newEvent.getCategory()).isEqualTo(originalEvent.getCategory()); assertThat(newEvent.getDate()).isEqualTo(originalEvent.getDate()); assertThat(newEvent.getCreatedAt()).isEqualTo(originalEvent.getCreatedAt()); } @Test public void ws_response_with_updated_name() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); EventDto originalEvent = db.events().insertEvent(newEvent(analysis).setUuid("E1").setName("Original Name")); ProjectAnalyses.Event result = call("E1", "name").getEvent(); assertThat(result.getName()).isEqualTo("name"); assertThat(result.hasDescription()).isFalse(); assertThat(result.getCategory()).isEqualTo(OTHER.name()); assertThat(result.getAnalysis()).isEqualTo(originalEvent.getAnalysisUuid()); assertThat(result.getKey()).isEqualTo("E1"); } @Test public void update_VERSION_event_update_analysis_version() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(VERSION.getLabel())); call("E1", "6.3"); SnapshotDto updatedAnalysis = dbClient.snapshotDao().selectByUuid(dbSession, analysis.getUuid()).get(); assertThat(updatedAnalysis.getProjectVersion()).isEqualTo("6.3"); } @Test public void update_OTHER_event_does_not_update_analysis_version() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(OTHER.getLabel())); call("E1", "6.3"); SnapshotDto updatedAnalysis = dbClient.snapshotDao().selectByUuid(dbSession, analysis.getUuid()).get(); assertThat(updatedAnalysis.getProjectVersion()).isEqualTo("5.6"); } @Test public void update_name_only_in_db() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); EventDto originalEvent = db.events().insertEvent(newEvent(analysis).setUuid("E1").setName("Original Name").setDescription("Original Description")); call("E1", "name"); EventDto newEvent = dbClient.eventDao().selectByUuid(dbSession, "E1").get(); assertThat(newEvent.getName()).isEqualTo("name"); assertThat(newEvent.getDescription()).isEqualTo(originalEvent.getDescription()); } @Test public void test_ws_definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("update_event"); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.isPost()).isTrue(); assertThat(definition.since()).isEqualTo("6.3"); assertThat(definition.param(PARAM_EVENT).isRequired()).isTrue(); assertThat(definition.param(PARAM_NAME).isRequired()).isTrue(); } @Test public void throw_ForbiddenException_if_not_project_administrator() { ComponentDto project = ComponentTesting.newPrivateProjectDto(); SnapshotDto analysis = db.components().insertProjectAndSnapshot(project); db.events().insertEvent(newEvent(analysis).setUuid("E1")); userSession.logIn().addProjectPermission(UserRole.USER, project); assertThatThrownBy(() -> call("E1", "name")) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_event_is_not_found() { userSession.logIn().setSystemAdministrator(); assertThatThrownBy(() -> call("E42", "name")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Event 'E42' not found"); } @Test public void fail_if_no_name() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1")); assertThatThrownBy(() -> call("E1", null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_if_blank_name() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1")); assertThatThrownBy(() -> call("E1", " ")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("A non empty name is required"); } @Test public void fail_if_category_other_than_other_or_version() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory("Profile")); assertThatThrownBy(() -> call("E1", "name")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Event of category 'QUALITY_PROFILE' cannot be modified."); } @Test public void fail_if_other_event_with_same_name_on_same_analysis() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(OTHER.getLabel()).setName("E1 name")); db.events().insertEvent(newEvent(analysis).setUuid("E2").setCategory(OTHER.getLabel()).setName("E2 name")); assertThatThrownBy(() -> call("E2", "E1 name")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("An 'Other' event with the same name already exists on analysis '" + analysis.getUuid() + "'"); } @Test public void limit_version_name_length_to_100_for_analysis_events() { SnapshotDto analysis = createAnalysisAndLogInAsProjectAdministrator("5.6"); db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory(OTHER.getLabel()).setName("E1 name")); db.events().insertEvent(newEvent(analysis).setUuid("E2").setCategory(VERSION.getLabel()).setName("E2 name")); call("E1", repeat("a", 100)); call("E1", repeat("a", 101)); call("E2", repeat("a", 100)); assertThatThrownBy(() -> call("E2", repeat("a", 101))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Event name length (101) is longer than the maximum authorized (100). " + "'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' was provided"); } private UpdateEventResponse call(@Nullable String eventUuid, @Nullable String name) { TestRequest request = ws.newRequest() .setMethod(POST.name()); ofNullable(eventUuid).ifPresent(e -> request.setParam(PARAM_EVENT, e)); ofNullable(name).ifPresent(n -> request.setParam(PARAM_NAME, n)); return request.executeProtobuf(UpdateEventResponse.class); } private void logInAsProjectAdministrator(ComponentDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } private SnapshotDto createAnalysisAndLogInAsProjectAdministrator(String version) { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); SnapshotDto analysis = db.components().insertSnapshot(newAnalysis(project).setProjectVersion(version)); logInAsProjectAdministrator(project); return analysis; } }
10,961
41.488372
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectdump/ws/ExportActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectdump.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.api.web.UserRole; import org.sonar.ce.task.CeTask; import org.sonar.db.DbTester; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.ce.projectdump.ExportSubmitter; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.test.JsonAssert.assertJson; public class ExportActionIT { private static final String TASK_ID = "THGTpxcB-iU5OvuD2ABC"; private static final String PROJECT_ID = "ABCTpxcB-iU5Ovuds4rf"; private static final String PROJECT_KEY = "the_project_key"; private static final String PROJECT_NAME = "The Project Name"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final ExportSubmitter exportSubmitter = mock(ExportSubmitter.class); private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT, Qualifiers.VIEW); private final ProjectDumpWsSupport projectDumpWsSupport = new ProjectDumpWsSupport(db.getDbClient(), userSession, new ComponentFinder(db.getDbClient(), resourceTypes)); private final ExportAction underTest = new ExportAction(projectDumpWsSupport, userSession, exportSubmitter); private final WsActionTester actionTester = new WsActionTester(underTest); private ProjectDto project; @Before public void setUp() { project = db.components().insertPrivateProject(PROJECT_ID, p -> p.setKey(PROJECT_KEY).setName(PROJECT_NAME)).getProjectDto(); } @Test public void response_example_is_defined() { assertThat(responseExample()).isNotEmpty(); } @Test public void fails_if_missing_project_key() { logInAsProjectAdministrator("foo"); assertThatThrownBy(() -> actionTester.newRequest().setMethod("POST").execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The 'key' parameter is missing"); } @Test public void fails_if_not_project_administrator() { userSession.logIn(); TestRequest request = actionTester.newRequest().setMethod("POST").setParam("key", project.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } @Test public void triggers_CE_task() { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(UserRole.ADMIN, project); when(exportSubmitter.submitProjectExport(project.getKey(), user.getUuid())).thenReturn(createResponseExampleTask()); TestResponse response = actionTester.newRequest().setMethod("POST").setParam("key", project.getKey()).execute(); assertJson(response.getInput()).isSimilarTo(responseExample()); } @Test public void fails_to_trigger_task_if_anonymous() { userSession.anonymous(); TestRequest request = actionTester.newRequest().setMethod("POST").setParam("key", project.getKey()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class) .hasMessage("Insufficient privileges"); } @Test public void triggers_CE_task_if_project_admin() { UserDto user = db.users().insertUser(); userSession.logIn(user).addProjectPermission(UserRole.ADMIN, project); when(exportSubmitter.submitProjectExport(project.getKey(), user.getUuid())).thenReturn(createResponseExampleTask()); TestResponse response = actionTester.newRequest().setMethod("POST").setParam("key", project.getKey()).execute(); assertJson(response.getInput()).isSimilarTo(responseExample()); } private void logInAsProjectAdministrator(String login) { userSession.logIn(login).addProjectPermission(UserRole.ADMIN, project); } private String responseExample() { return actionTester.getDef().responseExampleAsString(); } private CeTask createResponseExampleTask() { CeTask.Component component = new CeTask.Component(project.getUuid(), project.getKey(), project.getName()); return new CeTask.Builder() .setType(CeTaskTypes.PROJECT_EXPORT) .setUuid(TASK_ID) .setComponent(component) .setEntity(component) .build(); } }
5,598
37.881944
170
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectdump/ws/StatusActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectdump.ws; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.Slug; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ResourceTypesRule; import org.sonar.db.component.SnapshotTesting; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static java.util.Comparator.reverseOrder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.test.JsonAssert.assertJson; public class StatusActionIT { private static final String SOME_UUID = "some uuid"; private static final String ID_PARAM = "id"; private static final String KEY_PARAM = "key"; private static final String SOME_KEY = "some key"; @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final ResourceTypesRule resourceTypes = new ResourceTypesRule().setRootQualifiers(PROJECT); private final static String projectDumpsDirectoryPathname = "data/governance/project_dumps/"; private final static String importDirectoryPathname = Paths.get(projectDumpsDirectoryPathname, "import").toString(); private final static String exportDirectoryPathname = Paths.get(projectDumpsDirectoryPathname, "export").toString(); private ProjectDto project; private WsActionTester underTest; private final Configuration config = mock(Configuration.class); @Before public void setUp() throws Exception { project = insertProject(SOME_UUID, SOME_KEY); logInAsProjectAdministrator("user"); when(config.get("sonar.path.data")).thenReturn(Optional.of("data")); underTest = new WsActionTester(new StatusAction(dbClient, userSession, new ComponentFinder(dbClient, resourceTypes), config)); cleanUpFilesystem(); } @AfterClass public static void cleanUp() throws Exception { cleanUpFilesystem(); } @Test public void definition() { WebService.Action definition = underTest.getDef(); assertThat(definition.key()).isEqualTo("status"); assertThat(definition.isPost()).isFalse(); assertThat(definition.description()).isNotEmpty(); assertThat(definition.since()).isEqualTo("1.0"); assertThat(definition.isInternal()).isTrue(); assertThat(definition.responseExampleFormat()).isEqualTo("json"); assertThat(definition.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("id", false), tuple("key", false)); } @Test public void fails_with_BRE_if_no_param_is_provided() { assertThatThrownBy(() -> underTest.newRequest().execute()) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key must be provided, not both."); } @Test public void fails_with_BRE_if_both_params_are_provided() { assertThatThrownBy(() -> { underTest.newRequest() .setParam(ID_PARAM, SOME_UUID).setParam(KEY_PARAM, SOME_KEY) .execute(); }) .isInstanceOf(BadRequestException.class) .hasMessage("Project id or project key must be provided, not both."); } @Test public void fails_with_NFE_if_component_with_uuid_does_not_exist() { String UNKOWN_UUID = "UNKOWN_UUID"; assertThatThrownBy(() -> { underTest.newRequest() .setParam(ID_PARAM, UNKOWN_UUID) .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Project '" + UNKOWN_UUID + "' not found"); } @Test public void fails_with_NFE_if_component_with_key_does_not_exist() { String UNKNOWN_KEY = "UNKNOWN_KEY"; assertThatThrownBy(() -> { underTest.newRequest() .setParam(KEY_PARAM, UNKNOWN_KEY) .execute(); }) .isInstanceOf(NotFoundException.class) .hasMessage("Project '" + UNKNOWN_KEY + "' not found"); } @Test public void project_without_snapshot_can_be_imported_but_not_exported() { String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"canBeExported\":false,\"canBeImported\":true}"); } @Test public void project_with_snapshots_but_none_is_last_can_neither_be_imported_nor_exported() { insertSnapshot(project, false); insertSnapshot(project, false); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"canBeExported\":false,\"canBeImported\":false}"); } @Test public void project_with_is_last_snapshot_can_be_exported_but_not_imported() { insertSnapshot(project, false); insertSnapshot(project, true); insertSnapshot(project, false); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"canBeExported\":true,\"canBeImported\":false}"); } @Test public void exportedDump_field_contains_absolute_path_if_file_exists_and_is_regular_file() throws IOException { final String exportDumpFilePath = ensureDumpFileExists(SOME_KEY, false); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"exportedDump\":\"" + exportDumpFilePath + "\"}"); } @Test public void exportedDump_field_contains_absolute_path_if_file_exists_and_is_link() throws IOException { final String exportDumpFilePath = ensureDumpFileExists(SOME_KEY, false); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"exportedDump\":\"" + exportDumpFilePath + "\"}"); } @Test public void exportedDump_field_not_sent_if_file_is_directory() throws IOException { Files.createDirectories(Paths.get(exportDirectoryPathname)); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertThat(response) .doesNotContain("exportedDump"); } @Test public void dumpToImport_field_contains_absolute_path_if_file_exists_and_is_regular_file() throws IOException { final String importDumpFilePath = ensureDumpFileExists(SOME_KEY, true); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"dumpToImport\":\"" + importDumpFilePath + "\"}"); } @Test public void dumpToImport_field_contains_absolute_path_if_file_exists_and_is_link() throws IOException { final String importDumpFilePath = ensureDumpFileExists(SOME_KEY, true); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertJson(response) .isSimilarTo("{\"dumpToImport\":\"" + importDumpFilePath + "\"}"); } @Test public void dumpToImport_field_not_sent_if_file_is_directory() throws IOException { Files.createDirectories(Paths.get(importDirectoryPathname)); String response = underTest.newRequest() .setParam(KEY_PARAM, SOME_KEY) .execute() .getInput(); assertThat(response) .doesNotContain("dumpToImport"); } @Test public void fail_when_using_branch_id() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(project); assertThatThrownBy(() -> { underTest.newRequest() .setParam(ID_PARAM, branch.uuid()) .execute(); }) .isInstanceOf(NotFoundException.class); } private ProjectDto insertProject(String uuid, String key) { return db.components().insertPrivateProject(c -> c.setBranchUuid(uuid).setUuid(uuid).setKey(key)).getProjectDto(); } private void insertSnapshot(ProjectDto projectDto, boolean last) { dbClient.snapshotDao().insert(dbSession, SnapshotTesting.newAnalysis(projectDto.getUuid()).setLast(last)); dbSession.commit(); } private void logInAsProjectAdministrator(String login) { userSession.logIn(login).addProjectPermission(UserRole.ADMIN, project); } private String ensureDumpFileExists(String projectKey, boolean isImport) throws IOException { final String targetDirectoryPathname = isImport ? importDirectoryPathname : exportDirectoryPathname; final String dumpFilename = Slug.slugify(projectKey) + ".zip"; final String dumpFilePathname = Paths.get(targetDirectoryPathname, dumpFilename).toString(); final Path dumpFilePath = Paths.get(dumpFilePathname); File fileToImport = new File(dumpFilePathname); fileToImport.getParentFile().mkdirs(); Files.createFile(dumpFilePath); return dumpFilePathname; } private static void cleanUpFilesystem() throws IOException { final Path projectDumpsDirectoryPath = Paths.get(projectDumpsDirectoryPathname); if (Files.exists(projectDumpsDirectoryPath)) { Files.walk(projectDumpsDirectoryPath) .sorted(reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } }
11,124
32.408408
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/CreateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectlink.ws; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectLinks; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_NAME; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_URL; import static org.sonar.test.JsonAssert.assertJson; public class CreateActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final WsActionTester ws = new WsActionTester(new CreateAction(dbClient, userSession, TestComponentFinder.from(db), UuidFactoryFast.getInstance())); @Test public void example_with_key() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); logInAsProjectAdministrator(project); String result = ws.newRequest() .setMethod("POST") .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute().getInput(); assertJson(result).ignoreFields("id").isSimilarTo(getClass().getResource("create-example.json")); } @Test public void example_with_id() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); logInAsProjectAdministrator(project); String result = ws.newRequest() .setMethod("POST") .setParam(PARAM_PROJECT_ID, project.getUuid()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute().getInput(); assertJson(result).ignoreFields("id").isSimilarTo(getClass().getResource("create-example.json")); } @Test public void require_project_admin() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); logInAsProjectAdministrator(project); createAndTest(project); } @Test public void with_long_name() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); logInAsProjectAdministrator(project); String longName = StringUtils.leftPad("", 60, "a"); String expectedType = StringUtils.leftPad("", 20, "a"); createAndTest(project, longName, "http://example.org", expectedType); } @Test public void fail_if_no_name() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_long_name() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, StringUtils.leftPad("", 129, "*")) .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_no_url() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "Custom") .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_long_url() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "random") .setParam(PARAM_URL, StringUtils.leftPad("", 2049, "*")) .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_no_project() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "unknown") .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_anonymous() { userSession.anonymous(); ProjectData projectData = db.components().insertPublicProject(); ComponentDto project = projectData.getMainBranchComponent(); userSession.registerProjects(projectData.getProjectDto()); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_project_admin() { userSession.logIn(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_directory() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = db.components().insertComponent(ComponentTesting.newDirectory(project, "A/B")); failIfNotAProjectWithKey(project, directory); failIfNotAProjectWithUuid(project, directory); } @Test public void fail_if_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); failIfNotAProjectWithKey(project, file); failIfNotAProjectWithUuid(project, file); } @Test public void fail_if_view() { ComponentDto view = db.components().insertPrivatePortfolio(); failIfNotAProjectWithKey(view, view); failIfNotAProjectWithUuid(view, view); } @Test public void fail_when_using_branch_db_uuid() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.USER, project); ComponentDto branch = db.components().insertProjectBranch(project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } @Test public void define_create_action() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isPost()).isTrue(); assertThat(action.handler()).isNotNull(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()).hasSize(4); } private void failIfNotAProjectWithKey(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .setParam(PARAM_PROJECT_KEY, component.getKey()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project '" + component.getKey() + "' not found"); } private void failIfNotAProjectWithUuid(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(UserRole.ADMIN, root); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "Custom") .setParam(PARAM_URL, "http://example.org") .setParam(PARAM_PROJECT_ID, component.uuid()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project '" + component.uuid() + "' not found"); } private void createAndTest(ProjectDto project, String name, String url, String type) { ProjectLinks.CreateWsResponse response = ws.newRequest() .setMethod("POST") .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_NAME, name) .setParam(PARAM_URL, url) .executeProtobuf(ProjectLinks.CreateWsResponse.class); String newId = response.getLink().getId(); ProjectLinkDto link = dbClient.projectLinkDao().selectByUuid(dbSession, newId); assertThat(link.getName()).isEqualTo(name); assertThat(link.getHref()).isEqualTo(url); assertThat(link.getType()).isEqualTo(type); } private void createAndTest(ProjectDto project) { createAndTest(project, "Custom", "http://example.org", "custom"); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.ADMIN, project); } }
10,392
35.212544
157
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/DeleteActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectlink.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_ID; public class DeleteActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final WsActionTester ws = new WsActionTester(new DeleteAction(dbClient, userSession)); @Test public void no_response() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); TestResponse response = deleteLink(link); assertThat(response.getStatus()).isEqualTo(204); assertThat(response.getInput()).isEmpty(); } @Test public void remove_custom_link() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); deleteLink(link); assertLinkIsDeleted(link.getUuid()); } @Test public void keep_links_of_another_project() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto customLink1 = db.projectLinks().insertCustomLink(project1); ProjectLinkDto customLink2 = db.projectLinks().insertCustomLink(project2); userSession.logIn().addProjectPermission(ADMIN, project1, project2); deleteLink(customLink1); assertLinkIsDeleted(customLink1.getUuid()); assertLinkIsNotDeleted(customLink2.getUuid()); } @Test public void fail_when_delete_provided_link() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertProvidedLink(project); logInAsProjectAdministrator(project); assertThatThrownBy(() -> deleteLink(link)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Provided link cannot be deleted"); } @Test public void fail_on_unknown_link() { assertThatThrownBy(() -> ws.newRequest() .setMethod("POST") .setParam(PARAM_ID, "UNKNOWN") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_anonymous() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); userSession.anonymous(); assertThatThrownBy(() -> deleteLink(link)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_not_project_admin() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); userSession.logIn(); assertThatThrownBy(() -> deleteLink(link)) .isInstanceOf(ForbiddenException.class); } @Test public void define_delete_action() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isPost()).isTrue(); assertThat(action.handler()).isNotNull(); assertThat(action.responseExample()).isNull(); assertThat(action.params()).hasSize(1); } private TestResponse deleteLink(ProjectLinkDto link) { return ws.newRequest() .setMethod("POST") .setParam(PARAM_ID, link.getUuid()) .execute(); } private void assertLinkIsDeleted(String uuid) { assertThat(dbClient.projectLinkDao().selectByUuid(dbSession, uuid)).isNull(); } private void assertLinkIsNotDeleted(String uuid) { assertThat(dbClient.projectLinkDao().selectByUuid(dbSession, uuid)).isNotNull(); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(ADMIN, project); } }
5,599
34
96
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projectlink/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projectlink.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectLinks.Link; import org.sonarqube.ws.ProjectLinks.SearchWsResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID; import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY; import static org.sonar.test.JsonAssert.assertJson; public class SearchActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final WsActionTester ws = new WsActionTester(new SearchAction(dbClient, userSession, TestComponentFinder.from(db))); @Test public void example() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.projectLinks().insertProvidedLink(project, l -> l.setUuid("1").setType("homepage").setName("Homepage").setHref("http://example.org")); db.projectLinks().insertCustomLink(project, l -> l.setUuid("2").setType("custom").setName("Custom").setHref("http://example.org/custom")); logInAsProjectAdministrator(project); String result = ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute().getInput(); assertJson(result).isSimilarTo(getClass().getResource("search-example.json")); } @Test public void request_by_project_id() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); SearchWsResponse response = callByUuid(project.getUuid()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::getName) .containsExactlyInAnyOrder(tuple(link.getUuid(), link.getName())); } @Test public void request_by_project_key() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); SearchWsResponse response = callByKey(project.getKey()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::getName) .containsExactlyInAnyOrder(tuple(link.getUuid(), link.getName())); } @Test public void response_fields() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto homepageLink = db.projectLinks().insertProvidedLink(project); ProjectLinkDto customLink = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); SearchWsResponse response = callByKey(project.getKey()); assertThat(response.getLinksList()).extracting(Link::getId, Link::getName, Link::getType, Link::getUrl) .containsExactlyInAnyOrder( tuple(homepageLink.getUuid(), "", homepageLink.getType(), homepageLink.getHref()), tuple(customLink.getUuid(), customLink.getName(), customLink.getType(), customLink.getHref())); } @Test public void several_projects() { ProjectDto project1 = db.components().insertPrivateProject().getProjectDto(); ProjectDto project2 = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link1 = db.projectLinks().insertCustomLink(project1); ProjectLinkDto link2 = db.projectLinks().insertCustomLink(project2); userSession.addProjectPermission(USER, project1); userSession.addProjectPermission(USER, project2); SearchWsResponse response = callByKey(project1.getKey()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::getName) .containsExactlyInAnyOrder(tuple(link1.getUuid(), link1.getName())); } @Test public void request_does_not_fail_when_link_has_no_name() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertProvidedLink(project); logInAsProjectAdministrator(project); SearchWsResponse response = callByKey(project.getKey()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::hasName) .containsExactlyInAnyOrder(tuple(link.getUuid(), false)); } @Test public void project_administrator_can_search_for_links() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); logInAsProjectAdministrator(project); SearchWsResponse response = callByKey(project.getKey()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::getName) .containsExactlyInAnyOrder(tuple(link.getUuid(), link.getName())); } @Test public void project_user_can_search_for_links() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ProjectLinkDto link = db.projectLinks().insertCustomLink(project); userSession.logIn().addProjectPermission(USER, project); SearchWsResponse response = callByKey(project.getKey()); assertThat(response.getLinksList()) .extracting(Link::getId, Link::getName) .containsExactlyInAnyOrder(tuple(link.getUuid(), link.getName())); } @Test public void fail_when_no_project() { assertThatThrownBy(() -> callByKey("unknown")) .isInstanceOf(NotFoundException.class); } @Test public void fail_if_directory() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = db.components().insertComponent(ComponentTesting.newDirectory(project, "A/B")); failIfNotAProjectWithKey(project, directory); failIfNotAProjectWithUuid(project, directory); } @Test public void fail_if_file() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project)); failIfNotAProjectWithKey(project, file); failIfNotAProjectWithUuid(project, file); } @Test public void fail_if_view() { ComponentDto view = db.components().insertPrivatePortfolio(); failIfNotAProjectWithKey(view, view); failIfNotAProjectWithUuid(view, view); } @Test public void fail_if_insufficient_privileges() { userSession.anonymous(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); assertThatThrownBy(() -> callByKey(project.getKey())) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_both_id_and_key_are_provided() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); logInAsProjectAdministrator(project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PROJECT_ID, project.getUuid()) .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_no_id_nor_key_are_provided() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .setParam(PARAM_PROJECT_ID, project.uuid()) .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_using_branch_db_uuid() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(USER, project); ComponentDto branch = db.components().insertProjectBranch(project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_ID, branch.uuid()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } @Test public void define_search_action() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isPost()).isFalse(); assertThat(action.handler()).isNotNull(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()).hasSize(2); } private SearchWsResponse callByKey(String projectKey) { return ws.newRequest() .setParam(PARAM_PROJECT_KEY, projectKey) .executeProtobuf(SearchWsResponse.class); } private SearchWsResponse callByUuid(String projectUuid) { return ws.newRequest() .setParam(PARAM_PROJECT_ID, projectUuid) .executeProtobuf(SearchWsResponse.class); } private void logInAsProjectAdministrator(ProjectDto project) { userSession.logIn().addProjectPermission(ADMIN, project); } private void failIfNotAProjectWithKey(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(USER, root); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, component.getKey()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project '" + component.getKey() + "' not found"); } private void failIfNotAProjectWithUuid(ComponentDto root, ComponentDto component) { userSession.logIn().addProjectPermission(USER, root); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_ID, component.uuid()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Project '" + component.uuid() + "' not found"); } }
11,223
37.703448
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projecttag/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projecttag.ws; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.server.es.EsTester; import org.sonar.server.measure.index.ProjectMeasuresDoc; import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresIndexer; import org.sonar.server.permission.index.IndexPermissions; import org.sonar.server.permission.index.PermissionIndexerTester; import org.sonar.server.permission.index.WebAuthorizationTypeSupport; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.ProjectTags.SearchResponse; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.stream; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES; import static org.sonar.test.JsonAssert.assertJson; public class SearchActionIT { @Rule public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private ProjectMeasuresIndexer projectMeasureIndexer = new ProjectMeasuresIndexer(null, es.client()); private PermissionIndexerTester authorizationIndexer = new PermissionIndexerTester(es, projectMeasureIndexer); private ProjectMeasuresIndex index = new ProjectMeasuresIndex(es.client(), new WebAuthorizationTypeSupport(userSession), System2.INSTANCE); private WsActionTester ws = new WsActionTester(new SearchAction(index)); @Test public void json_example() { index(newDoc().setTags(newArrayList("official", "offshore", "playoff"))); String result = ws.newRequest().execute().getInput(); assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(result); } @Test public void search_by_query_and_page_size() { index( newDoc().setTags(newArrayList("whatever-tag", "official", "offshore", "yet-another-tag", "playoff")), newDoc().setTags(newArrayList("offshore", "playoff"))); SearchResponse result = call("off", 2); assertThat(result.getTagsList()).containsOnly("offshore", "official"); } @Test public void search_in_lexical_order() { index(newDoc().setTags(newArrayList("offshore", "official", "Playoff"))); SearchResponse result = call(null, null); assertThat(result.getTagsList()).containsExactly("Playoff", "official", "offshore"); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.key()).isEqualTo("search"); assertThat(definition.isInternal()).isFalse(); assertThat(definition.isPost()).isFalse(); assertThat(definition.responseExampleAsString()).isNotEmpty(); assertThat(definition.since()).isEqualTo("6.4"); assertThat(definition.params()).extracting(WebService.Param::key).containsOnly("q", "p", "ps"); } private void index(ProjectMeasuresDoc... docs) { es.putDocuments(TYPE_PROJECT_MEASURES, docs); authorizationIndexer.allow(stream(docs).map(doc -> new IndexPermissions(doc.getId(), PROJECT).allowAnyone()).collect(toList())); } private static ProjectMeasuresDoc newDoc(ComponentDto project) { return new ProjectMeasuresDoc() .setId(project.uuid()) .setKey(project.getKey()) .setName(project.name()); } private static ProjectMeasuresDoc newDoc() { return newDoc(ComponentTesting.newPrivateProjectDto()); } private SearchResponse call(@Nullable String textQuery, @Nullable Integer pageSize) { TestRequest request = ws.newRequest(); ofNullable(textQuery).ifPresent(s -> request.setParam("q", s)); ofNullable(pageSize).ifPresent(ps -> request.setParam("ps", ps.toString())); return request.executeProtobuf(SearchResponse.class); } }
5,039
38.069767
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/projecttag/ws/SetActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.projecttag.ws; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.es.TestIndexers; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.projecttag.TagsWsSupport; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.component.ComponentDbTester.defaults; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_TAGS_UPDATE; public class SetActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone().logIn(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final TestIndexers indexers = new TestIndexers(); private final TagsWsSupport tagsWsSupport = new TagsWsSupport(dbClient, TestComponentFinder.from(db), userSession, indexers, System2.INSTANCE); private final WsActionTester ws = new WsActionTester(new SetAction(dbClient, tagsWsSupport)); private ProjectDto project; private ComponentDto projectComponent; @Before public void setUp() { ProjectData projectData = db.components().insertPrivateProject(); project = projectData.getProjectDto(); projectComponent = projectData.getMainBranchComponent(); userSession.addProjectPermission(ADMIN, project); } @Test public void set_tags_exclude_empty_and_blank_values() { TestResponse response = call(project.getKey(), "finance , offshore, platform, ,"); assertTags(project.getKey(), "finance", "offshore", "platform"); indexers.hasBeenCalledForEntity(project.getUuid(), PROJECT_TAGS_UPDATE); assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void reset_tags() { project = db.components().insertPrivateProject(defaults(), p -> p.setTagsString("platform,scanner")).getProjectDto(); userSession.addProjectPermission(ADMIN, project); call(project.getKey(), ""); assertNoTags(project.getKey()); } @Test public void override_existing_tags() { project = db.components().insertPrivateProject(defaults(), p -> p.setTagsString("marketing,languages")).getProjectDto(); userSession.addProjectPermission(ADMIN, project); call(project.getKey(), "finance,offshore,platform"); assertTags(project.getKey(), "finance", "offshore", "platform"); } @Test public void set_tags_as_project_admin() { userSession.logIn().addProjectPermission(ADMIN, project); call(project.getKey(), "platform, lambda"); assertTags(project.getKey(), "platform", "lambda"); indexers.hasBeenCalledForEntity(project.getUuid(), PROJECT_TAGS_UPDATE); } @Test public void do_not_duplicate_tags() { call(project.getKey(), "atlas, atlas, atlas"); assertTags(project.getKey(), "atlas"); } @Test public void fail_if_tag_does_not_respect_format() { String projectKey = project.getKey(); assertThatThrownBy(() -> call(projectKey, "_finance_")) .isInstanceOf(BadRequestException.class) .hasMessage("Tag '_finance_' is invalid. Tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); } @Test public void fail_if_not_project_admin() { userSession.logIn().addProjectPermission(USER, project); String projectKey = project.getKey(); assertThatThrownBy(() -> call(projectKey, "platform")) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_no_project() { assertThatThrownBy(() -> call(null, "platform")) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_no_tags() { String projectKey = project.getKey(); assertThatThrownBy(() -> call(projectKey, null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_if_component_is_a_view() { ComponentDto view = db.components().insertPrivatePortfolio(v -> v.setKey("VIEW_KEY")); String viewKey = view.getKey(); assertThatThrownBy(() -> call(viewKey, "point-of-view")) .isInstanceOf(NotFoundException.class) .hasMessage("Project 'VIEW_KEY' not found"); } @Test public void fail_if_component_is_a_file() { ComponentDto file = db.components().insertComponent(newFileDto(projectComponent).setKey("FILE_KEY")); String fileKey = file.getKey(); assertThatThrownBy(() -> call(fileKey, "secret")) .isInstanceOf(NotFoundException.class) .hasMessage("Project 'FILE_KEY' not found"); } @Test public void definition() { WebService.Action definition = ws.getDef(); assertThat(definition.isPost()).isTrue(); assertThat(definition.isInternal()).isFalse(); assertThat(definition.params()).extracting(WebService.Param::key) .containsOnly("project", "tags"); assertThat(definition.description()).isNotEmpty(); assertThat(definition.since()).isEqualTo("6.4"); } private TestResponse call(@Nullable String projectKey, @Nullable String tags) { TestRequest request = ws.newRequest(); ofNullable(projectKey).ifPresent(p -> request.setParam("project", p)); ofNullable(tags).ifPresent(t -> request.setParam("tags", tags)); return request.execute(); } private void assertTags(String projectKey, String... tags) { assertThat(dbClient.projectDao().selectProjectByKey(dbSession, projectKey).get().getTags()).containsExactlyInAnyOrder(tags); } private void assertNoTags(String projectKey) { assertThat(dbClient.projectDao().selectProjectByKey(dbSession, projectKey).get().getTags()).isEmpty(); } }
7,396
35.800995
145
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/QualityGateCaycCheckerIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate; import java.util.List; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.Metric; import org.sonar.core.util.Uuids; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import static org.junit.Assert.assertEquals; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES; import static org.sonar.api.measures.CoreMetrics.LINE_COVERAGE; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY; import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING; import static org.sonar.server.qualitygate.QualityGateCaycChecker.CAYC_METRICS; import static org.sonar.server.qualitygate.QualityGateCaycStatus.COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.OVER_COMPLIANT; public class QualityGateCaycCheckerIT { @Rule public DbTester db = DbTester.create(); QualityGateCaycChecker underTest = new QualityGateCaycChecker(db.getDbClient()); @Test public void checkCaycCompliant() { String qualityGateUuid = "abcd"; CAYC_METRICS.forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getBestValue())); assertEquals(COMPLIANT, underTest.checkCaycCompliant(db.getSession(), qualityGateUuid)); } @Test public void check_Cayc_non_compliant_with_extra_conditions() { String qualityGateUuid = "abcd"; CAYC_METRICS.forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getBestValue())); // extra conditions outside of CAYC requirements List.of(LINE_COVERAGE, DUPLICATED_LINES).forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getBestValue())); assertEquals(OVER_COMPLIANT, underTest.checkCaycCompliant(db.getSession(), qualityGateUuid)); } @Test public void check_Cayc_NonCompliant_with_lesser_threshold_value() { var metrics = CAYC_METRICS.stream().map(this::insertMetric).toList(); IntStream.range(0, 4).forEach(idx -> { String qualityGateUuid = "abcd" + idx; for (int i = 0; i < metrics.size(); i++) { var metric = metrics.get(i); insertCondition(metric, qualityGateUuid, idx == i ? metric.getWorstValue() : metric.getBestValue()); } assertEquals(NON_COMPLIANT, underTest.checkCaycCompliant(db.getSession(), qualityGateUuid)); }); } @Test public void check_Cayc_NonCompliant_with_missing_metric() { String qualityGateUuid = "abcd"; List.of(NEW_MAINTAINABILITY_RATING, NEW_RELIABILITY_RATING, NEW_SECURITY_HOTSPOTS_REVIEWED, NEW_DUPLICATED_LINES_DENSITY) .forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getBestValue())); assertEquals(NON_COMPLIANT, underTest.checkCaycCompliant(db.getSession(), qualityGateUuid)); } @Test public void existency_requirements_check_only_existency() { String qualityGateUuid = "abcd"; List.of(NEW_MAINTAINABILITY_RATING, NEW_RELIABILITY_RATING, NEW_SECURITY_HOTSPOTS_REVIEWED, NEW_SECURITY_RATING) .forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getBestValue())); List.of(NEW_COVERAGE, NEW_DUPLICATED_LINES_DENSITY) .forEach(metric -> insertCondition(insertMetric(metric), qualityGateUuid, metric.getWorstValue())); assertEquals(COMPLIANT, underTest.checkCaycCompliant(db.getSession(), qualityGateUuid)); } private void insertCondition(MetricDto metricDto, String qualityGateUuid, Double threshold) { QualityGateConditionDto newCondition = new QualityGateConditionDto().setQualityGateUuid(qualityGateUuid) .setUuid(Uuids.create()) .setMetricUuid(metricDto.getUuid()) .setOperator("LT") .setErrorThreshold(threshold.toString()); db.getDbClient().gateConditionDao().insert(newCondition, db.getSession()); db.commit(); } private MetricDto insertMetric(Metric metric) { return db.measures().insertMetric(m -> m .setKey(metric.key()) .setValueType(metric.getType().name()) .setHidden(false) .setBestValue(metric.getBestValue()) .setBestValue(metric.getWorstValue()) .setDirection(metric.getDirection())); } }
5,484
43.959016
142
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/QualityGateConditionsUpdaterIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.measures.Metric; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; import static org.sonar.api.measures.Metric.ValueType.BOOL; import static org.sonar.api.measures.Metric.ValueType.DATA; import static org.sonar.api.measures.Metric.ValueType.DISTRIB; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.MILLISEC; import static org.sonar.api.measures.Metric.ValueType.PERCENT; import static org.sonar.api.measures.Metric.ValueType.RATING; import static org.sonar.api.measures.Metric.ValueType.STRING; import static org.sonar.api.measures.Metric.ValueType.WORK_DUR; @RunWith(DataProviderRunner.class) public class QualityGateConditionsUpdaterIT { @Rule public DbTester db = DbTester.create(); private final QualityGateConditionsUpdater underTest = new QualityGateConditionsUpdater(db.getDbClient()); @Test public void create_error_condition() { MetricDto metric = insertMetric(INT, "new_coverage"); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto result = underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80"); verifyCondition(result, qualityGate, metric, "LT", "80"); } @Test @UseDataProvider("valid_operators_and_direction") public void create_condition_with_valid_operators_and_direction(String operator, int direction) { MetricDto metric = db.measures().insertMetric(m -> m.setKey("key").setValueType(INT.name()).setHidden(false).setDirection(direction)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto result = underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), operator, "80"); verifyCondition(result, qualityGate, metric, operator, "80"); } @Test public void create_condition_throws_NPE_if_errorThreshold_is_null() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("errorThreshold can not be null"); } @Test public void fail_to_create_condition_when_condition_on_same_metric_already_exist() { MetricDto metric = insertMetric(PERCENT); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Condition on metric '%s' already exists.", metric.getShortName())); } @Test public void fail_to_create_condition_on_missing_metric() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, "new_coverage", "LT", "80")) .isInstanceOf(NotFoundException.class) .hasMessageContaining("There is no metric with key=new_coverage"); } @Test @UseDataProvider("invalid_metrics") public void fail_to_create_condition_on_invalid_metric(String metricKey, Metric.ValueType valueType, boolean hidden) { MetricDto metric = db.measures().insertMetric(m -> m.setKey(metricKey).setValueType(valueType.name()).setHidden(hidden).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", "80")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Metric '%s' cannot be used to define a condition", metric.getKey())); } @Test @UseDataProvider("invalid_operators_and_direction") public void fail_to_create_condition_on_not_allowed_operator_for_metric_direction(String operator, int direction) { MetricDto metric = db.measures().insertMetric(m -> m.setKey("key").setValueType(INT.name()).setHidden(false).setDirection(direction)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), operator, "90")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Operator %s is not allowed for this metric.", operator)); } @Test public void create_condition_on_rating_metric() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto result = underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "3"); verifyCondition(result, qualityGate, metric, "GT", "3"); } @Test public void fail_to_create_error_condition_on_invalid_rating_metric() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "80")) .isInstanceOf(BadRequestException.class) .hasMessageContaining("'80' is not a valid rating"); } @Test public void fail_to_create_condition_on_rating_greater_than_E() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "GT", "5")) .isInstanceOf(BadRequestException.class) .hasMessageContaining("There's no worse rating than E (5)"); } @Test @UseDataProvider("valid_values") public void create_error_condition(Metric.ValueType valueType, String value) { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(valueType.name()).setHidden(false).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto result = underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", value); verifyCondition(result, qualityGate, metric, "LT", value); } @Test @UseDataProvider("invalid_values") public void fail_to_create_error_INT_condition_when_value_is_not_an_integer(Metric.ValueType valueType, String value) { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(valueType.name()).setHidden(false).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> underTest.createCondition(db.getSession(), qualityGate, metric.getKey(), "LT", value)) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); } @Test public void update_condition() { MetricDto metric = insertMetric(PERCENT); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); QualityGateConditionDto result = underTest.updateCondition(db.getSession(), condition, metric.getKey(), "LT", "80"); verifyCondition(result, qualityGate, metric, "LT", "80"); } @Test public void update_condition_throws_NPE_if_errorThreshold_is_null() { MetricDto metric = insertMetric(PERCENT); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("errorThreshold can not be null"); } @Test public void update_condition_on_rating_metric() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); QualityGateConditionDto result = underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "4"); verifyCondition(result, qualityGate, metric, "GT", "4"); } @Test @UseDataProvider("update_invalid_operators_and_direction") public void fail_to_update_condition_on_not_allowed_operator_for_metric_direction(String validOperator, String updatedOperator, int direction) { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(PERCENT.name()).setHidden(false).setDirection(direction)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator(validOperator).setErrorThreshold("80")); assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), updatedOperator, "70")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Operator %s is not allowed for this metric", updatedOperator)); } @Test public void fail_to_update_condition_on_rating_metric_on_new_code_period() { MetricDto metric = insertMetric(RATING, SQALE_RATING_KEY); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("3")); QualityGateConditionDto result = underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "4"); verifyCondition(result, qualityGate, metric, "GT", "4"); } @Test public void fail_to_update_condition_on_rating_metric_on_not_core_rating_metric() { MetricDto metric = insertMetric(RATING, "not_core_rating_metric"); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("3")); assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "4")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("The metric '%s' cannot be used", metric.getShortName())); } @Test @UseDataProvider("invalid_metrics") public void fail_to_update_condition_on_invalid_metric(String metricKey, Metric.ValueType valueType, boolean hidden) { MetricDto metric = db.measures().insertMetric(m -> m.setKey(metricKey).setValueType(valueType.name()).setHidden(hidden)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "GT", "60")) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Metric '%s' cannot be used to define a condition", metric.getKey())); } @Test @UseDataProvider("valid_values") public void update_error_condition(Metric.ValueType valueType, String value) { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(valueType.name()).setHidden(false).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); QualityGateConditionDto result = underTest.updateCondition(db.getSession(), condition, metric.getKey(), "LT", value); verifyCondition(result, qualityGate, metric, "LT", value); } @Test @UseDataProvider("invalid_values") public void fail_to_update_error_INT_condition_when_value_is_not_an_integer(Metric.ValueType valueType, String value) { MetricDto metric = db.measures().insertMetric(m -> m.setValueType(valueType.name()).setHidden(false).setDirection(0)); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); assertThatThrownBy(() -> underTest.updateCondition(db.getSession(), condition, metric.getKey(), "LT", value)) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Invalid value '%s' for metric '%s'", value, metric.getShortName())); } @DataProvider public static Object[][] invalid_metrics() { return new Object[][] { {ALERT_STATUS_KEY, INT, false}, {SECURITY_HOTSPOTS_KEY, INT, false}, {NEW_SECURITY_HOTSPOTS_KEY, INT, false}, {"boolean", BOOL, false}, {"string", STRING, false}, {"data_metric", DATA, false}, {"distrib", DISTRIB, false}, {"hidden", INT, true} }; } @DataProvider public static Object[][] valid_values() { return new Object[][] { {INT, "10"}, {MILLISEC, "1000"}, {WORK_DUR, "1000"}, {FLOAT, "5.12"}, {PERCENT, "10.30"}, }; } @DataProvider public static Object[][] invalid_values() { return new Object[][] { {INT, "ABCD"}, {MILLISEC, "ABCD"}, {WORK_DUR, "ABCD"}, {FLOAT, "ABCD"}, {PERCENT, "ABCD"}, }; } @DataProvider public static Object[][] invalid_operators_and_direction() { return new Object[][] { {"EQ", 0}, {"NE", 0}, {"LT", -1}, {"GT", 1}, }; } @DataProvider public static Object[][] update_invalid_operators_and_direction() { return new Object[][] { {"LT", "EQ", 0}, {"LT", "NE", 0}, {"GT", "LT", -1}, {"LT", "GT", 1}, }; } @DataProvider public static Object[][] valid_operators_and_direction() { return new Object[][] { {"LT", 0}, {"GT", 0}, {"GT", -1}, {"LT", 1}, }; } private MetricDto insertMetric(Metric.ValueType type) { return insertMetric(type, "key"); } private MetricDto insertMetric(Metric.ValueType type, String key) { return db.measures().insertMetric(m -> m .setKey(key) .setValueType(type.name()) .setHidden(false) .setDirection(0)); } private void verifyCondition(QualityGateConditionDto dto, QualityGateDto qualityGate, MetricDto metric, String operator, String error) { QualityGateConditionDto reloaded = db.getDbClient().gateConditionDao().selectByUuid(dto.getUuid(), db.getSession()); assertThat(reloaded.getQualityGateUuid()).isEqualTo(qualityGate.getUuid()); assertThat(reloaded.getMetricUuid()).isEqualTo(metric.getUuid()); assertThat(reloaded.getOperator()).isEqualTo(operator); assertThat(reloaded.getErrorThreshold()).isEqualTo(error); assertThat(dto.getQualityGateUuid()).isEqualTo(qualityGate.getUuid()); assertThat(dto.getMetricUuid()).isEqualTo(metric.getUuid()); assertThat(dto.getOperator()).isEqualTo(operator); assertThat(dto.getErrorThreshold()).isEqualTo(error); } }
17,271
43.173913
146
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/QualityGateUpdaterIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateUpdaterIT { static final String QGATE_NAME = "Default"; @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final QualityGateUpdater underTest = new QualityGateUpdater(dbClient, UuidFactoryFast.getInstance()); @Test public void create_quality_gate() { QualityGateDto result = underTest.create(dbSession, QGATE_NAME); assertThat(result).isNotNull(); assertThat(result.getName()).isEqualTo(QGATE_NAME); assertThat(result.getCreatedAt()).isNotNull(); assertThat(result.isBuiltIn()).isFalse(); QualityGateDto reloaded = dbClient.qualityGateDao().selectByName(dbSession, QGATE_NAME); assertThat(reloaded).isNotNull(); } @Test public void fail_to_create_when_name_already_exists() { underTest.create(dbSession, QGATE_NAME); assertThatThrownBy(() -> underTest.create(dbSession, QGATE_NAME)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Name has already been taken"); } }
2,335
34.938462
111
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/RegisterQualityGatesIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDao; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDao; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDao; import org.sonar.db.qualitygate.QualityGateDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT_KEY; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.PERCENT; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.db.qualitygate.QualityGateConditionDto.OPERATOR_GREATER_THAN; import static org.sonar.db.qualitygate.QualityGateConditionDto.OPERATOR_LESS_THAN; public class RegisterQualityGatesIT { @Rule public DbTester db = DbTester.create(); @Rule public LogTester logTester = new LogTester(); private static final String BUILT_IN_NAME = "Sonar way"; private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final QualityGateDao qualityGateDao = dbClient.qualityGateDao(); private final QualityGateConditionDao gateConditionDao = dbClient.gateConditionDao(); private final MetricDao metricDao = dbClient.metricDao(); private final QualityGateConditionsUpdater qualityGateConditionsUpdater = new QualityGateConditionsUpdater(dbClient); private final RegisterQualityGates underTest = new RegisterQualityGates(dbClient, qualityGateConditionsUpdater, UuidFactoryFast.getInstance(), System2.INSTANCE); @Test public void register_default_gate() { insertMetrics(); underTest.start(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate [Sonar way] has been created"); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void upgrade_empty_quality_gate() { insertMetrics(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void upgrade_should_remove_deleted_condition() { insertMetrics(); QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate(); createBuiltInConditions(builtInQualityGate); // Add another condition qualityGateConditionsUpdater.createCondition(dbSession, builtInQualityGate, NEW_SECURITY_REMEDIATION_EFFORT_KEY, OPERATOR_GREATER_THAN, "5"); dbSession.commit(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void upgrade_should_remove_duplicated_conditions_if_found() { insertMetrics(); QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate(); createBuiltInConditions(builtInQualityGate); //Conditions added twice as found in some DB instances createBuiltInConditionsWithoutCheckingDuplicates(builtInQualityGate); dbSession.commit(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void upgrade_should_add_missing_condition() { insertMetrics(); QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate(); List<QualityGateConditionDto> builtInConditions = createBuiltInConditions(builtInQualityGate); // Remove a condition QualityGateConditionDto conditionToBeDeleted = builtInConditions.get(new Random().nextInt(builtInConditions.size())); gateConditionDao.delete(conditionToBeDeleted, dbSession); dbSession.commit(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void should_set_SonarWay_as_builtin_when_not_set() { insertMetrics(); QualityGateDto qualityGate = dbClient.qualityGateDao().insert(dbSession, new QualityGateDto() .setName("Sonar way") .setUuid(Uuids.createFast()) .setBuiltIn(false) .setCreatedAt(new Date())); dbSession.commit(); createBuiltInConditions(qualityGate); dbSession.commit(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Quality gate [Sonar way] has been set as built-in"); } @Test public void should_not_update_builtin_quality_gate_if_already_uptodate() { insertMetrics(); QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate(); createBuiltInConditions(builtInQualityGate); dbSession.commit(); underTest.start(); assertThat(db.countRowsOfTable("quality_gates")).isOne(); verifyCorrectBuiltInQualityGate(); // Log must not be present assertThat( logTester.logs(Level.INFO)).doesNotContain("Quality gate [Sonar way] has been set as built-in"); assertThat( logTester.logs(Level.INFO)).doesNotContain("Built-in quality gate [Sonar way] has been created"); assertThat( logTester.logs(Level.INFO)).doesNotContain("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void ensure_only_one_built_in_quality_gate() { insertMetrics(); String qualityGateName = "IncorrectQualityGate"; QualityGateDto builtin = new QualityGateDto().setName(qualityGateName).setBuiltIn(true).setUuid(Uuids.createFast()); qualityGateDao.insert(dbSession, builtin); dbSession.commit(); underTest.start(); QualityGateDto oldQualityGate = qualityGateDao.selectByName(dbSession, qualityGateName); assertThat(oldQualityGate).isNotNull(); assertThat(oldQualityGate.isBuiltIn()).isFalse(); assertThat(db.select("select name as \"name\" from quality_gates where is_built_in is true")) .extracting(column -> column.get("name")) .containsExactly(BUILT_IN_NAME); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate [Sonar way] has been created"); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } @Test public void builtin_quality_gate_with_incorrect_metricuuid_should_not_throw_an_exception() { insertMetrics(); QualityGateConditionDto conditionDto = new QualityGateConditionDto() .setUuid(Uuids.createFast()) .setQualityGateUuid("qgate_uuid") .setMetricUuid("unknown") // This uuid does not exist .setOperator(OPERATOR_GREATER_THAN) .setErrorThreshold("1"); gateConditionDao.insert(conditionDto, dbSession); dbSession.commit(); underTest.start(); // No exception thrown verifyCorrectBuiltInQualityGate(); assertThat( logTester.logs(Level.INFO)).contains("Built-in quality gate's conditions of [Sonar way] has been updated"); } private void insertMetrics() { dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_RELIABILITY_RATING_KEY).setValueType(INT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_SECURITY_RATING_KEY).setValueType(INT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_SECURITY_REMEDIATION_EFFORT_KEY).setValueType(INT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_MAINTAINABILITY_RATING_KEY).setValueType(PERCENT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_COVERAGE_KEY).setValueType(PERCENT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_DUPLICATED_LINES_DENSITY_KEY).setValueType(PERCENT.name()).setHidden(false).setDirection(0)); dbClient.metricDao().insert(dbSession, newMetricDto().setKey(NEW_SECURITY_HOTSPOTS_REVIEWED_KEY).setValueType(PERCENT.name()).setHidden(false).setDirection(0)); dbSession.commit(); } private void verifyCorrectBuiltInQualityGate() { MetricDto newReliability = metricDao.selectByKey(dbSession, NEW_RELIABILITY_RATING_KEY); MetricDto newSecurity = metricDao.selectByKey(dbSession, NEW_SECURITY_RATING_KEY); MetricDto newMaintainability = metricDao.selectByKey(dbSession, NEW_MAINTAINABILITY_RATING_KEY); MetricDto newCoverage = metricDao.selectByKey(dbSession, NEW_COVERAGE_KEY); MetricDto newDuplication = metricDao.selectByKey(dbSession, NEW_DUPLICATED_LINES_DENSITY_KEY); MetricDto newSecurityHotspots = metricDao.selectByKey(dbSession, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY); QualityGateDto qualityGateDto = qualityGateDao.selectByName(dbSession, BUILT_IN_NAME); assertThat(qualityGateDto).isNotNull(); assertThat(qualityGateDto.getCreatedAt()).isNotNull(); assertThat(qualityGateDto.isBuiltIn()).isTrue(); assertThat(gateConditionDao.selectForQualityGate(dbSession, qualityGateDto.getUuid())) .extracting(QualityGateConditionDto::getMetricUuid, QualityGateConditionDto::getOperator, QualityGateConditionDto::getErrorThreshold) .containsExactlyInAnyOrder( tuple(newReliability.getUuid(), OPERATOR_GREATER_THAN, "1"), tuple(newSecurity.getUuid(), OPERATOR_GREATER_THAN, "1"), tuple(newMaintainability.getUuid(), OPERATOR_GREATER_THAN, "1"), tuple(newCoverage.getUuid(), OPERATOR_LESS_THAN, "80"), tuple(newDuplication.getUuid(), OPERATOR_GREATER_THAN, "3"), tuple(newSecurityHotspots.getUuid(), OPERATOR_LESS_THAN, "100")); } private List<QualityGateConditionDto> createBuiltInConditions(QualityGateDto qg) { List<QualityGateConditionDto> conditions = new ArrayList<>(); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_SECURITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_RELIABILITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_MAINTAINABILITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_COVERAGE_KEY, OPERATOR_LESS_THAN, "80")); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_DUPLICATED_LINES_DENSITY_KEY, OPERATOR_GREATER_THAN, "3")); conditions.add(qualityGateConditionsUpdater.createCondition(dbSession, qg, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, OPERATOR_LESS_THAN, "100")); return conditions; } private List<QualityGateConditionDto> createBuiltInConditionsWithoutCheckingDuplicates(QualityGateDto qg) { List<QualityGateConditionDto> conditions = new ArrayList<>(); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_SECURITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_RELIABILITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_MAINTAINABILITY_RATING_KEY, OPERATOR_GREATER_THAN, "1")); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_COVERAGE_KEY, OPERATOR_LESS_THAN, "80")); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_DUPLICATED_LINES_DENSITY_KEY, OPERATOR_GREATER_THAN, "3")); conditions.add(createConditionWithoutCheckingDuplicates(qg, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, OPERATOR_LESS_THAN, "100")); return conditions; } private QualityGateConditionDto createConditionWithoutCheckingDuplicates(QualityGateDto qualityGate, String metricKey, String operator, String errorThreshold) { MetricDto metric = metricDao.selectByKey(dbSession, metricKey); QualityGateConditionDto newCondition = new QualityGateConditionDto().setQualityGateUuid(qualityGate.getUuid()) .setUuid(Uuids.create()) .setMetricUuid(metric.getUuid()).setMetricKey(metric.getKey()) .setOperator(operator) .setErrorThreshold(errorThreshold); gateConditionDao.insert(newCondition, dbSession); return newCondition; } }
14,749
44.384615
164
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/AddGroupActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; @RunWith(DataProviderRunner.class) public class AddGroupActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private final WsActionTester ws = new WsActionTester(new AddGroupAction(dbClient, uuidFactory, wsSupport)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("add_group"); assertThat(def.isPost()).isTrue(); assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("groupName", "gateName"); } @Test public void add_group() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertDefaultGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(response.getStatus()).isEqualTo(204); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGateDto, group)).isTrue(); } @Test public void does_nothing_when_group_can_already_edit_qualityGateDto() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertDefaultGroup(); db.qualityGates().addGroupPermission(qualityGateDto, group); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGateDto, group)).isTrue(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGateDto, group)).isTrue(); } @Test public void quality_gate_administers_can_add_group() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertDefaultGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGateDto, group)).isTrue(); } @Test public void quality_gate_editors_can_add_group() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); GroupDto originalGroup = db.users().insertDefaultGroup(); UserDto userAllowedToEditQualityGate = db.users().insertUser(); db.users().insertMember(originalGroup, userAllowedToEditQualityGate); db.qualityGates().addGroupPermission(qualityGateDto, originalGroup); userSession.logIn(userAllowedToEditQualityGate).setGroups(originalGroup); GroupDto newGroup = db.users().insertGroup(); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, newGroup.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGateDto, originalGroup)).isTrue(); } @Test public void fail_when_group_does_not_exist() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("Group with name 'unknown' is not found"); } @Test public void fail_when_qualityGateDto_does_not_exist() { GroupDto group = db.users().insertDefaultGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam(PARAM_GROUP_NAME, group.getName()); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("No quality gate has been found for name unknown"); } @Test public void fail_when_not_enough_permission() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertDefaultGroup(); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_GROUP_NAME, group.getName()); assertThatThrownBy(request::execute).isInstanceOf(ForbiddenException.class); } }
7,031
39.413793
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/AddUserActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; public class AddUserActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private final WsActionTester ws = new WsActionTester(new AddUserAction(dbClient, uuidFactory, wsSupport)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("add_user"); assertThat(def.isPost()).isTrue(); assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("login", "gateName"); } @Test public void add_user() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(response.getStatus()).isEqualTo(204); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGateDto, user)).isTrue(); } @Test public void does_nothing_when_user_can_already_edit_qualityGateDto() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGateDto, user); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGateDto, user)).isTrue(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGateDto, user)).isTrue(); } @Test public void quality_gate_administers_can_add_user() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGateDto, user)).isTrue(); } @Test public void quality_gate_editors_can_add_user() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); UserDto userAllowedToEditQualityGate = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGateDto, userAllowedToEditQualityGate); userSession.logIn(userAllowedToEditQualityGate); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGateDto, user)).isTrue(); } @Test public void fail_when_user_does_not_exist() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("User with login 'unknown' is not found"); } @Test public void fail_when_qualityGateDto_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam(PARAM_LOGIN, user.getLogin()); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("No quality gate has been found for name unknown"); } @Test public void fail_when_not_enough_permission() { QualityGateDto qualityGateDto = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGateDto.getName()) .setParam(PARAM_LOGIN, user.getLogin()); assertThatThrownBy(request::execute).isInstanceOf(ForbiddenException.class); } }
6,568
38.572289
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CopyActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateUpdater; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.QualityGate; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_SOURCE_NAME; @RunWith(DataProviderRunner.class) public class CopyActionIT { @Rule public final UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final QualityGateUpdater qualityGateUpdater = new QualityGateUpdater(dbClient, UuidFactoryFast.getInstance()); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)); private final CopyAction underTest = new CopyAction(dbClient, userSession, qualityGateUpdater, wsSupport); private final WsActionTester ws = new WsActionTester(underTest); @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isTrue(); assertThat(action.responseExampleAsString()).isNullOrEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("sourceName", true), tuple("name", true)); } @Test public void copy() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new-name") .execute(); QualityGateDto actual = db.getDbClient().qualityGateDao().selectByName(dbSession, "new-name"); assertThat(actual).isNotNull(); assertThat(actual.isBuiltIn()).isFalse(); assertThat(actual.getUuid()).isNotEqualTo(qualityGate.getUuid()); assertThat(actual.getUuid()).isNotEqualTo(qualityGate.getUuid()); assertThat(db.getDbClient().gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid())) .extracting(QualityGateConditionDto::getMetricUuid, QualityGateConditionDto::getErrorThreshold) .containsExactlyInAnyOrder(tuple(metric.getUuid(), condition.getErrorThreshold())); } @Test public void copy_of_builtin_should_not_be_builtin() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qualityGateDto -> qualityGateDto.setBuiltIn(true)); ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new-name") .execute(); QualityGateDto actual = db.getDbClient().qualityGateDao().selectByName(dbSession, "new-name"); assertThat(actual).isNotNull(); assertThat(actual.isBuiltIn()).isFalse(); } @Test public void response_contains_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGate response = ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new-name") .executeProtobuf(QualityGate.class); assertThat(response).isNotNull(); assertThat(response.getId()).isNotEqualTo(qualityGate.getUuid()); assertThat(response.getName()).isEqualTo("new-name"); } @Test public void fail_when_missing_administer_quality_gate_permission() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new-name") .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_source_name_parameter_is_missing() { userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "new-name") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'sourceName' parameter is missing"); } @Test public void fail_when_quality_gate_name_is_not_found() { userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_SOURCE_NAME, "unknown") .setParam(PARAM_NAME, "new-name") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate has been found for name unknown"); } @Test @UseDataProvider("nullOrEmpty") public void fail_when_name_parameter_is_missing(@Nullable String nameParameter) { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); TestRequest request = ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()); ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, t)); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @DataProvider public static Object[][] nullOrEmpty() { return new Object[][]{ {null}, {""}, {" "} }; } @Test public void fail_when_name_parameter_match_existing_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto existingQualityGate = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_SOURCE_NAME, qualityGate.getName()) .setParam(PARAM_NAME, existingQualityGate.getName()) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Name has already been taken"); } }
8,389
38.023256
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.measures.Metric; import org.sonar.api.server.ws.WebService; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.qualitygate.QualityGateConditionsUpdater; import org.sonar.server.qualitygate.QualityGateUpdater; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.CreateResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.QualityGateCaycChecker.CAYC_METRICS; import static org.sonar.server.qualitygate.ws.CreateAction.DEFAULT_METRIC_VALUES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; @RunWith(DataProviderRunner.class) public class CreateActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final CreateAction underTest = new CreateAction(dbClient, userSession, new QualityGateUpdater(dbClient, UuidFactoryFast.getInstance()), new QualityGateConditionsUpdater(dbClient)); private final WsActionTester ws = new WsActionTester(underTest); @Before public void setup() { CAYC_METRICS.forEach(this::insertMetric); } @Test public void create_quality_gate_with_cayc_conditions() { logInAsQualityGateAdmin(); String qgName = "Default"; CreateResponse response = executeRequest(qgName); assertThat(response.getName()).isEqualTo(qgName); dbSession.commit(); QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectByName(dbSession, qgName); assertThat(qualityGateDto).isNotNull(); var conditions = getConditions(dbSession, qualityGateDto); CAYC_METRICS.stream() .map(m -> dbClient.metricDao().selectByKey(dbSession, m.getKey())) .forEach(metricDto -> assertThat(conditions) .anyMatch(c -> metricDto.getUuid().equals(c.getMetricUuid()) && c.getErrorThreshold().equals(String.valueOf(getDefaultCaycValue(metricDto))))); } @Test public void test_ws_definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isTrue(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()).hasSize(1); } @Test public void throw_ForbiddenException_if_not_gate_administrator() { userSession.logIn(); assertThatThrownBy(() -> executeRequest("Default")) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void throw_BadRequestException_if_name_is_already_used() { userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); executeRequest("Default"); assertThatThrownBy(() -> executeRequest("Default")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Name has already been taken"); } @Test @UseDataProvider("nullOrEmpty") public void fail_when_name_parameter_is_empty(@Nullable String nameParameter) { userSession.addPermission(ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest(); Optional.ofNullable(nameParameter).ifPresent(t -> request.setParam(PARAM_NAME, "")); assertThatThrownBy(() -> request.execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @DataProvider public static Object[][] nullOrEmpty() { return new Object[][] { {null}, {""}, {" "} }; } private Collection<QualityGateConditionDto> getConditions(DbSession dbSession, QualityGateDto qualityGate) { return dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid()); } private CreateResponse executeRequest(String qualitGateName) { return ws.newRequest() .setParam("name", qualitGateName) .executeProtobuf(CreateResponse.class); } private void logInAsQualityGateAdmin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); } private void insertMetric(Metric metric) { db.measures().insertMetric(m -> m .setKey(metric.getKey()) .setValueType(metric.getType().name()) .setHidden(metric.isHidden()) .setDirection(metric.getDirection())); } private Integer getDefaultCaycValue(MetricDto metricDto) { return DEFAULT_METRIC_VALUES.containsKey(metricDto.getKey()) ? DEFAULT_METRIC_VALUES.get(metricDto.getKey()) : CAYC_METRICS.stream() .filter(metric -> metricDto.getKey().equals(metric.getKey())) .findAny() .orElseThrow() .getBestValue().intValue(); } }
6,536
34.917582
151
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/CreateConditionActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.qualitygate.QualityGateConditionsUpdater; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.CreateConditionResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ERROR; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_METRIC; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPERATOR; @RunWith(DataProviderRunner.class) public class CreateConditionActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final CreateConditionAction underTest = new CreateConditionAction(dbClient, new QualityGateConditionsUpdater(dbClient), new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db))); private final WsActionTester ws = new WsActionTester(underTest); @Test public void create_error_condition() { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute(); assertCondition(qualityGate, metric, "LT", "90"); } @Test public void create_condition_over_new_code_period() { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute(); assertCondition(qualityGate, metric, "LT", "90"); } @Test public void fail_to_update_built_in_quality_gate() { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); MetricDto metric = insertMetric(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_with_unknown_operator() { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(0)); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "ABC") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); } @Test @UseDataProvider("invalid_operators_for_direction") public void fail_with_invalid_operators_for_direction(String operator, int direction) { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(direction)); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, operator) .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Operator %s is not allowed for this metric.", operator)); } @Test public void test_response() { logInAsQualityGateAdmin(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); CreateConditionResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "45") .executeProtobuf(CreateConditionResponse.class); QualityGateConditionDto condition = new ArrayList<>(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid())).get(0); assertThat(response.getId()).isEqualTo(condition.getUuid()); assertThat(response.getMetric()).isEqualTo(metric.getKey()); assertThat(response.getOp()).isEqualTo("LT"); assertThat(response.getError()).isEqualTo("45"); } @Test public void user_with_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); userSession.logIn(user); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void user_with_group_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); UserDto user = db.users().insertUser(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); userSession.logIn(user).setGroups(group); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void throw_ForbiddenException_if_not_gate_administrator() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); userSession.logIn(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void test_ws_definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isTrue(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("gateName", true), tuple("metric", true), tuple("error", true), tuple("op", false)); } @DataProvider public static Object[][] invalid_operators_for_direction() { return new Object[][] { {"LT", -1}, {"GT", 1}, }; } private void assertCondition(QualityGateDto qualityGate, MetricDto metric, String operator, String error) { assertThat(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid())) .extracting(QualityGateConditionDto::getQualityGateUuid, QualityGateConditionDto::getMetricUuid, QualityGateConditionDto::getOperator, QualityGateConditionDto::getErrorThreshold) .containsExactlyInAnyOrder(tuple(qualityGate.getUuid(), metric.getUuid(), operator, error)); } private void logInAsQualityGateAdmin() { userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); } private MetricDto insertMetric() { return db.measures().insertMetric(m -> m .setValueType(INT.name()) .setHidden(false) .setDirection(0)); } }
10,446
37.549815
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DeleteConditionActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import java.util.Collection; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ID; public class DeleteConditionActionIT { @Rule public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private final WsActionTester ws = new WsActionTester( new DeleteConditionAction(db.getDbClient(), new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)))); @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.isPost()).isTrue(); assertThat(action.isInternal()).isFalse(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("id", true)); } @Test public void delete_condition() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute(); assertThat(searchConditionsOf(qualityGate)).isEmpty(); } @Test public void no_content() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); TestResponse result = ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute(); assertThat(result.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void user_with_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); userSession.logIn(user); TestResponse response = ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute(); assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void user_with_group_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); UserDto user = db.users().insertUser(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); userSession.logIn(user).setGroups(group); TestResponse response = ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute(); assertThat(response.getStatus()).isEqualTo(HTTP_NO_CONTENT); } @Test public void fail_if_built_in_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_if_not_quality_gate_administrator() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, qualityGateCondition.getUuid()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_condition_uuid_is_not_found() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(); QualityGateConditionDto qualityGateCondition = db.qualityGates().addCondition(qualityGate, metric); String unknownConditionUuid = "unknown"; assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, unknownConditionUuid) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate condition with uuid '" + unknownConditionUuid + "'"); } @Test public void fail_when_condition_match_unknown_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateConditionDto condition = new QualityGateConditionDto().setUuid("uuid").setMetricUuid("metric").setQualityGateUuid("123"); db.getDbClient().gateConditionDao().insert(condition, db.getSession()); db.commit(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .execute()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); } private Collection<QualityGateConditionDto> searchConditionsOf(QualityGateDto qualityGate) { return db.getDbClient().gateConditionDao().selectForQualityGate(db.getSession(), qualityGate.getUuid()); } }
7,834
40.020942
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DeselectActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; public class DeselectActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final ComponentFinder componentFinder = TestComponentFinder.from(db); private final DeselectAction underTest = new DeselectAction(dbClient, new QualityGatesWsSupport(db.getDbClient(), userSession, componentFinder)); private final WsActionTester ws = new WsActionTester(underTest); @Test public void deselect_by_key() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); associateProjectToQualityGate(project, qualityGate); ws.newRequest() .setParam("projectKey", project.getKey()) .execute(); assertDeselected(project); } @Test public void project_admin() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); associateProjectToQualityGate(project, qualityGate); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); ws.newRequest() .setParam("projectKey", project.getKey()) .execute(); assertDeselected(project); } @Test public void other_project_should_not_be_updated() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); associateProjectToQualityGate(project, qualityGate); // Another project ProjectDto anotherProject = db.components().insertPrivateProject().getProjectDto(); associateProjectToQualityGate(anotherProject, qualityGate); ws.newRequest() .setParam("projectKey", project.getKey()) .execute(); assertDeselected(project); assertSelected(qualityGate, anotherProject); } @Test public void default_is_used() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); associateProjectToQualityGate(project, qualityGate); ws.newRequest() .setParam("projectKey", project.getKey()) .execute(); assertDeselected(project); } @Test public void fail_when_no_project_key() { userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", "unknown") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_anonymous() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.anonymous(); assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_not_project_admin() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ISSUE_ADMIN, project); assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_not_quality_gates_admin() { userSession.addPermission(ADMINISTER_QUALITY_GATES); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().addPermission(ADMINISTER_QUALITY_PROFILES); assertThatThrownBy(() -> ws.newRequest() .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void definition() { WebService.Action def = ws.getDef(); assertThat(def.description()).isNotEmpty(); assertThat(def.isPost()).isTrue(); assertThat(def.since()).isEqualTo("4.3"); assertThat(def.changelog()).extracting(Change::getVersion, Change::getDescription).containsExactly( tuple("6.6", "The parameter 'gateId' was removed"), tuple("8.3", "The parameter 'projectId' was removed")); assertThat(def.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("projectKey", true)); } private void associateProjectToQualityGate(ProjectDto project, QualityGateDto qualityGate) { db.qualityGates().associateProjectToQualityGate(project, qualityGate); db.commit(); } private void assertDeselected(ProjectDto project) { Optional<String> qGateUuid = db.qualityGates().selectQGateUuidByProjectUuid(project.getUuid()); assertThat(qGateUuid) .isNotNull() .isEmpty(); } private void assertSelected(QualityGateDto qualityGate, ProjectDto project) { Optional<String> qGateUuid = db.qualityGates().selectQGateUuidByProjectUuid(project.getUuid()); assertThat(qGateUuid) .isNotNull() .isNotEmpty() .hasValue(qualityGate.getUuid()); } }
7,156
34.964824
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/DestroyActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.Pagination; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static java.lang.String.format; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.qualitygate.SearchQualityGatePermissionQuery.builder; import static org.sonar.db.user.SearchPermissionQuery.IN; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; public class DestroyActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGateFinder qualityGateFinder = new QualityGateFinder(dbClient); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)); private final DbSession dbSession = db.getSession(); private final DestroyAction underTest = new DestroyAction(dbClient, wsSupport, qualityGateFinder); private final WsActionTester ws = new WsActionTester(underTest); @Test public void delete_quality_gate() { db.qualityGates().createDefaultQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); userSession.addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute(); assertThat(db.getDbClient().qualityGateDao().selectByUuid(dbSession, qualityGate.getUuid())).isNull(); } @Test public void delete_quality_gate_if_non_default_when_a_default_exist() { db.qualityGates().createDefaultQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); userSession.addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute(); assertThat(db.getDbClient().qualityGateDao().selectByUuid(dbSession, qualityGate.getUuid())).isNull(); } @Test public void delete_quality_gate_and_any_association_to_any_project() { db.qualityGates().createDefaultQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto prj1 = db.components().insertPublicProject().getProjectDto(); ProjectDto prj2 = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(prj1, qualityGate); db.qualityGates().associateProjectToQualityGate(prj2, qualityGate); userSession.addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute(); assertThat(db.getDbClient().projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, prj1.getUuid())) .isEmpty(); assertThat(db.getDbClient().projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, prj2.getUuid())) .isEmpty(); assertThat(db.getDbClient().projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, prj1.getUuid())) .isEmpty(); assertThat(db.getDbClient().projectQgateAssociationDao().selectQGateUuidByProjectUuid(dbSession, prj2.getUuid())) .isEmpty(); } @Test public void delete_quality_gate_and_any_associated_group_permissions() { db.qualityGates().createDefaultQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group1); db.qualityGates().addGroupPermission(qualityGate, group2); userSession.addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute(); assertThat(db.getDbClient().qualityGateGroupPermissionsDao().selectByQuery(dbSession, builder() .setQualityGate(qualityGate) .setMembership(IN).build(), Pagination.all())) .isEmpty(); } @Test public void delete_quality_gate_and_any_associated_user_permissions() { db.qualityGates().createDefaultQualityGate(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user1); db.qualityGates().addUserPermission(qualityGate, user2); userSession.addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute(); assertThat(db.getDbClient().qualityGateUserPermissionDao().selectByQuery(dbSession, builder() .setQualityGate(qualityGate) .setMembership(IN).build(), Pagination.all())) .isEmpty(); } @Test public void does_not_delete_built_in_quality_gate() { db.qualityGates().createDefaultQualityGate(); QualityGateDto builtInQualityGate = db.qualityGates().insertBuiltInQualityGate(); db.commit(); userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, valueOf(builtInQualityGate.getName())) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", builtInQualityGate.getName())); } @Test public void fail_when_missing_name() { userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .execute()) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_to_delete_default_quality_gate() { QualityGateDto defaultQualityGate = db.qualityGates().createDefaultQualityGate(); userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, valueOf(defaultQualityGate.getName())) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The default quality gate cannot be removed"); } @Test public void fail_on_unknown_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, "unknown") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_not_quality_gates_administer() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().createDefaultQualityGate(); userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.isPost()).isTrue(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("name", true)); } }
8,866
37.219828
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/GetByProjectActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates; import org.sonarqube.ws.Qualitygates.GetByProjectResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.test.JsonAssert.assertJson; public class GetByProjectActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final WsActionTester ws = new WsActionTester( new GetByProjectAction(userSession, dbClient, TestComponentFinder.from(db), new QualityGateFinder(dbClient))); @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action.description()).isNotEmpty(); assertThat(action.isInternal()).isFalse(); assertThat(action.since()).isEqualTo("6.1"); assertThat(action.changelog()).isNotEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("project", true)); } @Test public void json_example() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.qualityGates().associateProjectToQualityGate(project, qualityGate); logInAsProjectUser(project); String result = ws.newRequest() .setParam("project", project.getKey()) .execute() .getInput(); assertJson(result) .isSimilarTo(getClass().getResource("get_by_project-example.json")); } @Test public void default_quality_gate() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(dbQualityGate); logInAsProjectUser(project); GetByProjectResponse result = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(GetByProjectResponse.class); Qualitygates.QualityGate qualityGate = result.getQualityGate(); assertThat(qualityGate.getName()).isEqualTo(dbQualityGate.getName()); assertThat(qualityGate.getDefault()).isTrue(); } @Test public void project_quality_gate_over_default() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto defaultDbQualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(defaultDbQualityGate); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().associateProjectToQualityGate(project, qualityGate); logInAsProjectUser(project); GetByProjectResponse result = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(GetByProjectResponse.class); Qualitygates.QualityGate reloaded = result.getQualityGate(); assertThat(reloaded.getName()).isEqualTo(reloaded.getName()); assertThat(reloaded.getDefault()).isFalse(); } @Test public void get_by_project_key() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My team QG")); db.qualityGates().associateProjectToQualityGate(project, qualityGate); logInAsProjectUser(project); GetByProjectResponse result = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(GetByProjectResponse.class); assertThat(result.getQualityGate().getName()).isEqualTo(qualityGate.getName()); } @Test public void get_with_project_admin_permission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); userSession.logIn().addProjectPermission(UserRole.ADMIN, project); GetByProjectResponse result = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(GetByProjectResponse.class); assertThat(result.getQualityGate().getName()).isEqualTo(qualityGate.getName()); } @Test public void get_with_project_user_permission() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); userSession.logIn().addProjectPermission(UserRole.USER, project); GetByProjectResponse result = ws.newRequest() .setParam("project", project.getKey()) .executeProtobuf(GetByProjectResponse.class); assertThat(result.getQualityGate().getName()).isEqualTo(qualityGate.getName()); } @Test public void fail_when_insufficient_permission() { QualityGateDto dbQualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(dbQualityGate); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); assertThatThrownBy(() -> ws.newRequest() .setParam("project", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_project_does_not_exist() { assertThatThrownBy(() -> ws.newRequest() .setParam("project", "Unknown") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_missing_project_parameter() { assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'project' parameter is missing"); } private void logInAsProjectUser(ProjectDto project) { userSession.logIn().addProjectPermission(UserRole.USER, project); } }
7,469
37.505155
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ListActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.qualitygate.QualityGateCaycChecker; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.ListWsResponse.QualityGate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.qualitygate.QualityGateCaycStatus.COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.OVER_COMPLIANT; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.Qualitygates.ListWsResponse; public class ListActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGateFinder qualityGateFinder = new QualityGateFinder(dbClient); private final QualityGateCaycChecker qualityGateCaycChecker = mock(QualityGateCaycChecker.class); private final WsActionTester ws = new WsActionTester(new ListAction(db.getDbClient(), new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)), qualityGateFinder, qualityGateCaycChecker)); @Before public void setUp() { when(qualityGateCaycChecker.checkCaycCompliant(any(), any())).thenReturn(COMPLIANT); } @Test public void list_quality_gates() { QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(defaultQualityGate); ListWsResponse response = ws.newRequest() .executeProtobuf(ListWsResponse.class); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, QualityGate::getIsDefault) .containsExactlyInAnyOrder( tuple(defaultQualityGate.getName(), true), tuple(otherQualityGate.getName(), false)); } @Test public void test_built_in_flag() { QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(qualityGate -> qualityGate.setBuiltIn(true)); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(qualityGate -> qualityGate.setBuiltIn(false)); db.qualityGates().setDefaultQualityGate(qualityGate1); ListWsResponse response = ws.newRequest() .executeProtobuf(ListWsResponse.class); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, QualityGate::getIsBuiltIn) .containsExactlyInAnyOrder( tuple(qualityGate1.getName(), true), tuple(qualityGate2.getName(), false)); } @Test public void test_caycStatus_flag() { QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate3 = db.qualityGates().insertQualityGate(); when(qualityGateCaycChecker.checkCaycCompliant(any(DbSession.class), eq(qualityGate1.getUuid()))).thenReturn(COMPLIANT); when(qualityGateCaycChecker.checkCaycCompliant(any(DbSession.class), eq(qualityGate2.getUuid()))).thenReturn(NON_COMPLIANT); when(qualityGateCaycChecker.checkCaycCompliant(any(DbSession.class), eq(qualityGate3.getUuid()))).thenReturn(OVER_COMPLIANT); db.qualityGates().setDefaultQualityGate(qualityGate1); ListWsResponse response = ws.newRequest() .executeProtobuf(ListWsResponse.class); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, QualityGate::getCaycStatus) .containsExactlyInAnyOrder( tuple(qualityGate1.getName(), COMPLIANT.toString()), tuple(qualityGate2.getName(), NON_COMPLIANT.toString()), tuple(qualityGate3.getName(), OVER_COMPLIANT.toString())); } @Test public void no_default_quality_gate() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .executeProtobuf(ListWsResponse.class)) .isInstanceOf(IllegalStateException.class); } @Test public void actions_with_quality_gate_administer_permission() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Default").setBuiltIn(false)); QualityGateDto builtInQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way").setBuiltIn(true)); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way - Without Coverage").setBuiltIn(false)); db.qualityGates().setDefaultQualityGate(defaultQualityGate); ListWsResponse response = ws.newRequest().executeProtobuf(ListWsResponse.class); assertThat(response.getActions()) .extracting(ListWsResponse.RootActions::getCreate) .isEqualTo(true); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, qg -> qg.getActions().getRename(), qg -> qg.getActions().getDelete(), qg -> qg.getActions().getManageConditions(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(), qp -> qp.getActions().getAssociateProjects(), qp -> qp.getActions().getDelegate()) .containsExactlyInAnyOrder( tuple(defaultQualityGate.getName(), true, false, true, true, false, false, true), tuple(builtInQualityGate.getName(), false, false, false, true, true, true, false), tuple(otherQualityGate.getName(), true, true, true, true, true, true, true)); } @Test public void actions_with_quality_gate_delegate_permission() { QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way")); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way - Without Coverage")); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(defaultQualityGate, user); db.qualityGates().addUserPermission(otherQualityGate, user); userSession.logIn(user); db.qualityGates().setDefaultQualityGate(defaultQualityGate); ListWsResponse response = ws.newRequest().executeProtobuf(ListWsResponse.class); assertThat(response.getActions()) .extracting(ListWsResponse.RootActions::getCreate) .isEqualTo(false); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, qg -> qg.getActions().getRename(), qg -> qg.getActions().getDelete(), qg -> qg.getActions().getManageConditions(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(), qp -> qp.getActions().getAssociateProjects(), qp -> qp.getActions().getDelegate()) .containsExactlyInAnyOrder( tuple(defaultQualityGate.getName(), false, false, true, false, false, false, true), tuple(otherQualityGate.getName(), false, false, true, false, false, false, true)); } @Test public void actions_without_quality_gate_administer_permission() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way").setBuiltIn(true)); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way - Without Coverage").setBuiltIn(false)); db.qualityGates().setDefaultQualityGate(defaultQualityGate); ListWsResponse response = ws.newRequest().executeProtobuf(ListWsResponse.class); assertThat(response.getActions()) .extracting(ListWsResponse.RootActions::getCreate) .isEqualTo(false); assertThat(response.getQualitygatesList()) .extracting(QualityGate::getName, qg -> qg.getActions().getRename(), qg -> qg.getActions().getDelete(), qg -> qg.getActions().getManageConditions(), qp -> qp.getActions().getCopy(), qp -> qp.getActions().getSetAsDefault(), qp -> qp.getActions().getAssociateProjects(), qp -> qp.getActions().getDelegate()) .containsExactlyInAnyOrder( tuple(defaultQualityGate.getName(), false, false, false, false, false, false, false), tuple(otherQualityGate.getName(), false, false, false, false, false, false, false)); } @Test public void json_example() { userSession.logIn("admin").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(qualityGate -> qualityGate.setName("Sonar way").setBuiltIn(true)); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(qualityGate -> qualityGate.setName("Sonar way - Without Coverage").setBuiltIn(false)); db.qualityGates().setDefaultQualityGate(defaultQualityGate); when(qualityGateCaycChecker.checkCaycCompliant(any(), eq(defaultQualityGate.getUuid()))).thenReturn(COMPLIANT); when(qualityGateCaycChecker.checkCaycCompliant(any(), eq(otherQualityGate.getUuid()))).thenReturn(NON_COMPLIANT); String response = ws.newRequest().execute().getInput(); assertJson(response).ignoreFields("default") .isSimilarTo(getClass().getResource("list-example.json")); } @Test public void verify_definition() { WebService.Action action = ws.getDef(); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.key()).isEqualTo("list"); assertThat(action.isPost()).isFalse(); assertThat(action.isInternal()).isFalse(); assertThat(action.changelog()).isNotEmpty(); assertThat(action.params()).extracting(WebService.Param::key, WebService.Param::isRequired).isEmpty(); } }
11,354
47.319149
160
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ProjectStatusActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateCaycChecker; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.ProjectStatusResponse; import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.Status; import static java.lang.String.format; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.SnapshotTesting.newAnalysis; import static org.sonar.db.measure.MeasureTesting.newLiveMeasure; import static org.sonar.db.measure.MeasureTesting.newMeasureDto; import static org.sonar.db.metric.MetricTesting.newMetricDto; import static org.sonar.server.qualitygate.QualityGateCaycStatus.COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ANALYSIS_ID; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_BRANCH; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_ID; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PROJECT_KEY; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PULL_REQUEST; import static org.sonar.test.JsonAssert.assertJson; public class ProjectStatusActionIT { private static final String ANALYSIS_ID = "task-uuid"; @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final QualityGateCaycChecker qualityGateCaycChecker = mock(QualityGateCaycChecker.class); private final WsActionTester ws = new WsActionTester(new ProjectStatusAction(dbClient, TestComponentFinder.from(db), userSession, qualityGateCaycChecker)); @Before public void setUp() { when(qualityGateCaycChecker.checkCaycCompliantFromProject(any(), any())).thenReturn(NON_COMPLIANT); } @Test public void test_definition() { WebService.Action action = ws.getDef(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("analysisId", false), tuple("projectKey", false), tuple("projectId", false), tuple("branch", false), tuple("pullRequest", false)); } @Test public void test_json_example() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); MetricDto gateDetailsMetric = insertGateDetailMetric(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); dbClient.measureDao().insert(dbSession, newMeasureDto(gateDetailsMetric, mainBranch, snapshot) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json"), StandardCharsets.UTF_8))); dbSession.commit(); String response = ws.newRequest() .setParam("analysisId", snapshot.getUuid()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_past_status_when_project_is_referenced_by_past_analysis_id() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto pastAnalysis = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch) .setLast(false) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); SnapshotDto lastAnalysis = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch) .setLast(true) .setPeriodMode("last_version") .setPeriodParam("2016-12-07") .setPeriodDate(1_500L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.measureDao().insert(dbSession, newMeasureDto(gateDetailsMetric, mainBranch, pastAnalysis) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbClient.measureDao().insert(dbSession, newMeasureDto(gateDetailsMetric, mainBranch, lastAnalysis) .setData("not_used")); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, pastAnalysis.getUuid()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_live_status_when_project_is_referenced_by_its_id() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(mainBranch, gateDetailsMetric) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_PROJECT_ID, projectData.projectUuid()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_past_status_when_branch_is_referenced_by_past_analysis_id() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); ComponentDto branch = db.components().insertProjectBranch(mainBranch); SnapshotDto pastAnalysis = dbClient.snapshotDao().insert(dbSession, newAnalysis(branch) .setLast(false) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); SnapshotDto lastAnalysis = dbClient.snapshotDao().insert(dbSession, newAnalysis(branch) .setLast(true) .setPeriodMode("last_version") .setPeriodParam("2016-12-07") .setPeriodDate(1_500L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.measureDao().insert(dbSession, newMeasureDto(gateDetailsMetric, branch, pastAnalysis) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbClient.measureDao().insert(dbSession, newMeasureDto(gateDetailsMetric, branch, lastAnalysis) .setData("not_used")); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, pastAnalysis.getUuid()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_live_status_when_project_is_referenced_by_its_key() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto project = projectData.getMainBranchComponent(); dbClient.snapshotDao().insert(dbSession, newAnalysis(project) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(project, gateDetailsMetric) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_PROJECT_KEY, project.getKey()) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_live_status_when_branch_is_referenced_by_its_key() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); String branchName = randomAlphanumeric(248); ComponentDto branch = db.components().insertProjectBranch(mainBranch, b -> b.setKey(branchName)); dbClient.snapshotDao().insert(dbSession, newAnalysis(branch) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(branch, gateDetailsMetric) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_PROJECT_KEY, mainBranch.getKey()) .setParam(PARAM_BRANCH, branchName) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_live_status_when_pull_request_is_referenced_by_its_key() throws IOException { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); String pullRequestKey = RandomStringUtils.randomAlphanumeric(100); ComponentDto pr = db.components().insertProjectBranch(mainBranch, branch -> branch.setBranchType(BranchType.PULL_REQUEST) .setKey(pullRequestKey)); dbClient.snapshotDao().insert(dbSession, newAnalysis(pr) .setPeriodMode("last_version") .setPeriodParam("2015-12-07") .setPeriodDate(956789123987L)); MetricDto gateDetailsMetric = insertGateDetailMetric(); dbClient.liveMeasureDao().insert(dbSession, newLiveMeasure(pr, gateDetailsMetric) .setData(IOUtils.toString(getClass().getResource("ProjectStatusActionIT/measure_data.json")))); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); String response = ws.newRequest() .setParam(PARAM_PROJECT_KEY, mainBranch.getKey()) .setParam(PARAM_PULL_REQUEST, pullRequestKey) .execute().getInput(); assertJson(response).isSimilarTo(getClass().getResource("project_status-example.json")); } @Test public void return_undefined_status_if_specified_analysis_is_not_found() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); ProjectStatusResponse result = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) .executeProtobuf(ProjectStatusResponse.class); assertThat(result.getProjectStatus().getStatus()).isEqualTo(Status.NONE); assertThat(result.getProjectStatus().getConditionsCount()).isZero(); } @Test public void return_undefined_status_if_project_is_not_analyzed() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); ProjectStatusResponse result = ws.newRequest() .setParam(PARAM_PROJECT_ID, projectData.projectUuid()) .executeProtobuf(ProjectStatusResponse.class); assertThat(result.getProjectStatus().getStatus()).isEqualTo(Status.NONE); assertThat(result.getProjectStatus().getConditionsCount()).isZero(); } @Test public void project_administrator_is_allowed_to_get_project_status() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addProjectPermission(UserRole.ADMIN, projectData.getProjectDto()); ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) .executeProtobuf(ProjectStatusResponse.class); } @Test public void project_user_is_allowed_to_get_project_status() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) .executeProtobuf(ProjectStatusResponse.class); } @Test public void check_cayc_compliant_flag() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); var qg = db.qualityGates().insertBuiltInQualityGate(); db.qualityGates().setDefaultQualityGate(qg); when(qualityGateCaycChecker.checkCaycCompliantFromProject(any(DbSession.class), eq(projectData.projectUuid()))).thenReturn(COMPLIANT); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addProjectPermission(UserRole.USER, projectData.getProjectDto()); ProjectStatusResponse result = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) .executeProtobuf(ProjectStatusResponse.class); assertEquals(COMPLIANT.toString(), result.getProjectStatus().getCaycStatus()); } @Test public void user_with_project_scan_permission_is_allowed_to_get_project_status() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addProjectPermission(UserRole.SCAN, projectData.getProjectDto()); var response = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()).execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void user_with_global_scan_permission_is_allowed_to_get_project_status() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.addPermission(GlobalPermission.SCAN); var response = ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()).execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void fail_if_no_snapshot_id_found() { logInAsSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, ANALYSIS_ID) .executeProtobuf(ProjectStatusResponse.class)) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Analysis with id 'task-uuid' is not found"); } @Test public void fail_if_insufficient_privileges() { ProjectData projectData = db.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); SnapshotDto snapshot = dbClient.snapshotDao().insert(dbSession, newAnalysis(mainBranch)); dbSession.commit(); userSession.logIn(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, snapshot.getUuid()) .executeProtobuf(ProjectStatusResponse.class)) .isInstanceOf(ForbiddenException.class); } @Test public void fail_if_project_id_and_ce_task_id_provided() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); logInAsSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ANALYSIS_ID, "analysis-id") .setParam(PARAM_PROJECT_ID, "project-uuid") .execute().getInput()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); } @Test public void fail_if_branch_key_and_pull_request_id_provided() { ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); logInAsSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_PROJECT_KEY, "key") .setParam(PARAM_BRANCH, "branch") .setParam(PARAM_PULL_REQUEST, "pr") .execute().getInput()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Either 'branch' or 'pullRequest' can be provided, not both"); } @Test public void fail_if_no_parameter_provided() { logInAsSystemAdministrator(); assertThatThrownBy(() -> ws.newRequest() .execute().getInput()) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Either 'analysisId', 'projectId' or 'projectKey' must be provided"); } @Test public void fail_when_using_branch_uuid() { ProjectData projectData = db.components().insertPublicProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); userSession.logIn().addProjectPermission(UserRole.ADMIN, projectData.getProjectDto()); ComponentDto branch = db.components().insertProjectBranch(mainBranch); SnapshotDto snapshot = db.components().insertSnapshot(branch); assertThatThrownBy(() -> ws.newRequest() .setParam("projectId", branch.uuid()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining(format("Project '%s' not found", branch.uuid())); } private void logInAsSystemAdministrator() { userSession.logIn().setSystemAdministrator(); } private MetricDto insertGateDetailMetric() { return dbClient.metricDao().insert(dbSession, newMetricDto() .setEnabled(true) .setKey(CoreMetrics.QUALITY_GATE_DETAILS_KEY)); } }
20,907
42.558333
157
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/RemoveGroupActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME; public class RemoveGroupActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)); private final WsActionTester ws = new WsActionTester(new RemoveGroupAction(dbClient, wsSupport)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("remove_group"); assertThat(def.isPost()).isTrue(); assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("groupName", "gateName"); } @Test public void remove_group() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(response.getStatus()).isEqualTo(204); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGate, group)).isFalse(); } @Test public void does_nothing_when_group_cannot_edit_gate() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGate, group)).isFalse(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGate, group)).isFalse(); } @Test public void qg_administrators_can_remove_group() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGate, group)).isFalse(); } @Test public void qg_editors_can_remove_group() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); UserDto userAllowedToEditGate = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, userAllowedToEditGate); userSession.logIn(userAllowedToEditGate); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute(); assertThat(dbClient.qualityGateGroupPermissionsDao().exists(db.getSession(), qualityGate, group)).isFalse(); } @Test public void fail_when_group_does_not_exist() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("Group with name 'unknown' is not found"); } @Test public void fail_when_qgate_does_not_exist() { GroupDto group = db.users().insertGroup(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam(PARAM_GROUP_NAME, group.getName()) .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining(String.format("No quality gate has been found for name unknown")); } @Test public void fail_when_qg_is_built_in() { GroupDto group = db.users().insertGroup(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(String.format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_when_not_enough_permission() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); userSession.logIn(db.users().insertUser()).addPermission(GlobalPermission.ADMINISTER_QUALITY_PROFILES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_GROUP_NAME, group.getName()) .execute()) .isInstanceOf(ForbiddenException.class); } }
7,232
39.183333
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/RemoveUserActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_LOGIN; public class RemoveUserActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db)); private final WsActionTester ws = new WsActionTester(new RemoveUserAction(dbClient, wsSupport)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("remove_user"); assertThat(def.isPost()).isTrue(); assertThat(def.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder("login", "gateName"); } @Test public void remove_user() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); TestResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(response.getStatus()).isEqualTo(204); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGate, user)).isFalse(); } @Test public void does_nothing_when_user_cannot_edit_gate() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGate, user)).isFalse(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGate, user)).isFalse(); } @Test public void qg_administrators_can_remove_user() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGate, user)).isFalse(); } @Test public void qg_editors_can_remove_user() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); UserDto userAllowedToEditGate = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, userAllowedToEditGate); userSession.logIn(userAllowedToEditGate); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()) .execute(); assertThat(dbClient.qualityGateUserPermissionDao().exists(db.getSession(), qualityGate, user)).isFalse(); } @Test public void fail_when_user_does_not_exist() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); final TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("User with login 'unknown' is not found"); } @Test public void fail_when_qgate_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); final TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam(PARAM_LOGIN, user.getLogin()); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("No quality gate has been found for name unknown"); } @Test public void fail_when_qg_is_built_in() { UserDto user = db.users().insertUser(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); final TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()); assertThatThrownBy(request::execute) .isInstanceOf(IllegalArgumentException.class) .hasMessage(String.format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_when_not_enough_permission() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()); final TestRequest request = ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam(PARAM_LOGIN, user.getLogin()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } }
7,133
37.771739
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/RenameActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.QualityGate; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_CURRENT_NAME; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; public class RenameActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final WsActionTester ws = new WsActionTester( new RenameAction(db.getDbClient(), new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)))); @Test public void verify_definition() { WebService.Action action = ws.getDef(); assertThat(action.key()).isEqualTo("rename"); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.changelog()).isNotEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple(PARAM_CURRENT_NAME, true), tuple(PARAM_NAME, true)); } @Test public void rename() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("old name")); userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new name") .execute(); assertThat(db.getDbClient().qualityGateDao().selectByUuid(db.getSession(), qualityGate.getUuid()).getName()).isEqualTo("new name"); } @Test public void response_contains_quality_gate() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("old name")); QualityGate result = ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new name") .executeProtobuf(QualityGate.class); assertThat(result.getId()).isEqualTo(qualityGate.getUuid()); assertThat(result.getName()).isEqualTo("new name"); } @Test public void rename_with_same_name() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName(PARAM_NAME)); ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "name") .execute(); assertThat(db.getDbClient().qualityGateDao().selectByUuid(db.getSession(), qualityGate.getUuid()).getName()).isEqualTo(PARAM_NAME); } @Test public void fail_on_built_in_quality_gate() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "name") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_on_empty_name() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_when_using_existing_name() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate1 = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate1.getName()) .setParam(PARAM_NAME, qualityGate2.getName()) .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Name '%s' has already been taken", qualityGate2.getName())); } @Test public void fail_on_unknown_quality_gate() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_CURRENT_NAME, "unknown") .setParam(PARAM_NAME, "new name") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_not_quality_gates_administer() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("old name")); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_CURRENT_NAME, qualityGate.getName()) .setParam(PARAM_NAME, "new name") .execute()) .isInstanceOf(ForbiddenException.class); } }
6,700
38.187135
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/SearchActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.SearchResponse; import org.sonarqube.ws.Qualitygates.SearchResponse.Result; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.api.server.ws.WebService.SelectionMode.ALL; import static org.sonar.api.server.ws.WebService.SelectionMode.DESELECTED; import static org.sonar.api.server.ws.WebService.SelectionMode.SELECTED; import static org.sonar.api.web.UserRole.USER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PAGE; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_PAGE_SIZE; import static org.sonarqube.ws.client.user.UsersWsParameters.PARAM_SELECTED; public class SearchActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final SearchAction underTest = new SearchAction(dbClient, userSession, new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db))); private final WsActionTester ws = new WsActionTester(underTest); @Test public void search_projects_of_a_quality_gate() { ComponentDto project = db.components().insertPublicProject().getMainBranchComponent(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().associateProjectToQualityGate(db.components().getProjectDtoByMainBranch(project), qualityGate); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()) .extracting(Result::getKey, Result::getName) .containsExactlyInAnyOrder(tuple(project.getKey(), project.name())); } @Test public void return_empty_association() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()).isEmpty(); } @Test public void return_all_projects() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto unassociatedProject = db.components().insertPublicProject().getProjectDto(); ProjectDto associatedProject = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(associatedProject, qualityGate); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()) .extracting(Result::getName, Result::getKey, Result::getSelected) .containsExactlyInAnyOrder( tuple(associatedProject.getName(), associatedProject.getKey(), true), tuple(unassociatedProject.getName(), unassociatedProject.getKey(), false)); } @Test public void return_only_associated_project() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto associatedProject = db.components().insertPublicProject().getProjectDto(); ProjectDto unassociatedProject = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(associatedProject, qualityGate); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, SELECTED.value()) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()) .extracting(Result::getName, Result::getSelected) .containsExactlyInAnyOrder(tuple(associatedProject.getName(), true)) .doesNotContain(tuple(unassociatedProject.getName(), false)); } @Test public void return_only_unassociated_project() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto associatedProject = db.components().insertPublicProject().getProjectDto(); ProjectDto unassociatedProject = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(associatedProject, qualityGate); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, DESELECTED.value()) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()) .extracting(Result::getName, Result::getSelected) .containsExactlyInAnyOrder(tuple(unassociatedProject.getName(), false)) .doesNotContain(tuple(associatedProject.getName(), true)); } @Test public void return_only_authorized_projects() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ComponentDto project1 = db.components().insertPrivateProject().getMainBranchComponent(); ComponentDto project2 = db.components().insertPrivateProject().getMainBranchComponent(); UserDto user = db.users().insertUser(); // User can only see project1 1 db.users().insertProjectPermissionOnUser(user, USER, project1); userSession.logIn(user); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .executeProtobuf(SearchResponse.class); assertThat(response.getResultsList()) .extracting(Result::getName) .containsExactlyInAnyOrder(project1.name()) .doesNotContain(project2.name()); } @Test public void test_paging() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project1 = db.components().insertPublicProject().getProjectDto(); ProjectDto project2 = db.components().insertPublicProject().getProjectDto(); ProjectDto project3 = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(project1, qualityGate); // Return partial result on first page assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .setParam(PARAM_PAGE, "1") .setParam(PARAM_PAGE_SIZE, "1") .executeProtobuf(SearchResponse.class) .getResultsList()) .extracting(Result::getName) .containsExactlyInAnyOrder(project1.getName()); // Return partial result on second page assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .setParam(PARAM_PAGE, "2") .setParam(PARAM_PAGE_SIZE, "1") .executeProtobuf(SearchResponse.class) .getResultsList()) .extracting(Result::getName) .containsExactlyInAnyOrder(project2.getName()); // Return partial result on first page assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .setParam(PARAM_PAGE, "1") .setParam(PARAM_PAGE_SIZE, "2") .executeProtobuf(SearchResponse.class) .getResultsList()) .extracting(Result::getName) .containsExactlyInAnyOrder(project1.getName(), project2.getName()); // Return all result on first page assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .setParam(PARAM_PAGE, "1") .setParam(PARAM_PAGE_SIZE, "3") .executeProtobuf(SearchResponse.class) .getResultsList()) .extracting(Result::getName) .containsExactlyInAnyOrder(project1.getName(), project2.getName(), project3.getName()); // Return no result as page index is off limit assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_SELECTED, ALL.value()) .setParam(PARAM_PAGE, "3") .setParam(PARAM_PAGE_SIZE, "3") .executeProtobuf(SearchResponse.class) .getResultsList()) .extracting(Result::getName) .isEmpty(); } @Test public void test_pagination_on_many_pages() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); for (int i = 0; i < 20; i++) { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(project, qualityGate); } userSession.addPermission(ADMINISTER_QUALITY_GATES); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_PAGE_SIZE, valueOf(5)) .setParam(PARAM_PAGE, valueOf(2)) .executeProtobuf(SearchResponse.class); assertThat(response) .extracting( searchResponse -> searchResponse.getPaging().getPageIndex(), searchResponse -> searchResponse.getPaging().getPageSize(), searchResponse -> searchResponse.getPaging().getTotal()) .contains(2, 5, 20); } @Test public void test_pagination_on_one_page() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); for (int i = 0; i < 20; i++) { ProjectDto project = db.components().insertPublicProject().getProjectDto(); db.qualityGates().associateProjectToQualityGate(project, qualityGate); } userSession.addPermission(ADMINISTER_QUALITY_GATES); SearchResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, valueOf(qualityGate.getName())) .setParam(PARAM_PAGE_SIZE, valueOf(100)) .setParam(PARAM_PAGE, valueOf(1)) .executeProtobuf(SearchResponse.class); assertThat(response) .extracting( searchResponse -> searchResponse.getPaging().getPageIndex(), searchResponse -> searchResponse.getPaging().getPageSize(), searchResponse -> searchResponse.getPaging().getTotal()) .contains(1, 100, 20); } @Test public void fail_on_unknown_quality_gate() { assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .executeProtobuf(SearchResponse.class)) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate has been found for name unknown"); } @Test public void definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isFalse(); assertThat(action.responseExampleAsString()).isNotEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("gateName", true), tuple("query", false), tuple("selected", false), tuple("page", false), tuple("pageSize", false)); } }
12,617
40.370492
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/SearchGroupsActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.user.GroupTesting.newGroupDto; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.MediaTypes.JSON; public class SearchGroupsActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)); private final WsActionTester ws = new WsActionTester(new SearchGroupsAction(db.getDbClient(), wsSupport)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("search_groups"); assertThat(def.isPost()).isFalse(); assertThat(def.params()).extracting(WebService.Param::key) .containsExactlyInAnyOrder("gateName", "selected", "q", "p", "ps"); } @Test public void test_example() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup(newGroupDto().setName("users").setDescription("Users")); GroupDto group2 = db.users().insertGroup(newGroupDto().setName("administrators").setDescription("Administrators")); db.qualityGates().addGroupPermission(gate, group1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); String result = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .setMediaType(JSON) .execute() .getInput(); assertJson(ws.getDef().responseExampleAsString()).isSimilarTo(result); } @Test public void search_all_groups() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName, Qualitygates.SearchGroupsResponse.Group::getDescription, Qualitygates.SearchGroupsResponse.Group::getSelected) .containsExactlyInAnyOrder( Assertions.tuple(group1.getName(), group1.getDescription(), true), Assertions.tuple(group2.getName(), group2.getDescription(), false)); } @Test public void search_selected_groups() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "selected") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName, Qualitygates.SearchGroupsResponse.Group::getDescription, Qualitygates.SearchGroupsResponse.Group::getSelected) .containsExactlyInAnyOrder( Assertions.tuple(group1.getName(), group1.getDescription(), true)); } @Test public void search_deselected_groups() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup(); GroupDto group2 = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "deselected") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName, Qualitygates.SearchGroupsResponse.Group::getDescription, Qualitygates.SearchGroupsResponse.Group::getSelected) .containsExactlyInAnyOrder( Assertions.tuple(group2.getName(), group2.getDescription(), false)); } @Test public void search_by_name() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group1 = db.users().insertGroup("sonar-users-project"); GroupDto group2 = db.users().insertGroup("sonar-users-qgate"); GroupDto group3 = db.users().insertGroup("sonar-admin"); db.qualityGates().addGroupPermission(gate, group1); db.qualityGates().addGroupPermission(gate, group2); db.qualityGates().addGroupPermission(gate, group3); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(TEXT_QUERY, "UsErS") .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()).extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactlyInAnyOrder(group1.getName(), group2.getName()); } @Test public void group_without_description() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(newGroupDto().setDescription(null)); db.qualityGates().addGroupPermission(gate, group); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName, Qualitygates.SearchGroupsResponse.Group::hasDescription) .containsExactlyInAnyOrder(Assertions.tuple(group.getName(), false)); } @Test public void paging_search() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group3 = db.users().insertGroup("group3"); GroupDto group1 = db.users().insertGroup("group1"); GroupDto group2 = db.users().insertGroup("group2"); db.qualityGates().addGroupPermission(gate, group1); db.qualityGates().addGroupPermission(gate, group2); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .setParam(PAGE, "1") .setParam(PAGE_SIZE, "1") .executeProtobuf(Qualitygates.SearchGroupsResponse.class).getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactly(group1.getName()); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .setParam(PAGE, "3") .setParam(PAGE_SIZE, "1") .executeProtobuf(Qualitygates.SearchGroupsResponse.class).getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactly(group3.getName()); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .setParam(PAGE, "1") .setParam(PAGE_SIZE, "10") .executeProtobuf(Qualitygates.SearchGroupsResponse.class).getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactly(group1.getName(), group2.getName(), group3.getName()); } @Test public void uses_global_permission() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactlyInAnyOrder(group.getName()); } @Test public void qg_administers_can_search_groups() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group); userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactlyInAnyOrder(group.getName()); } @Test public void qg_editors_can_search_groups() { QualityGateDto gate = db.qualityGates().insertQualityGate(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(gate, group); UserDto userAllowedToEditQualityGate = db.users().insertUser(); db.qualityGates().addUserPermission(gate, userAllowedToEditQualityGate); userSession.logIn(userAllowedToEditQualityGate); Qualitygates.SearchGroupsResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(WebService.Param.SELECTED, "all") .executeProtobuf(Qualitygates.SearchGroupsResponse.class); assertThat(response.getGroupsList()) .extracting(Qualitygates.SearchGroupsResponse.Group::getName) .containsExactlyInAnyOrder(group.getName()); } @Test public void fail_when_qgate_does_not_exist() { userSession.logIn().addPermission(GlobalPermission.ADMINISTER_QUALITY_GATES); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate has been found for name unknown"); } @Test public void fail_when_not_enough_permission() { QualityGateDto gate = db.qualityGates().insertQualityGate(); userSession.logIn(db.users().insertUser()); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .execute()) .isInstanceOf(ForbiddenException.class); } }
12,734
41.45
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/SearchUsersActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.issue.AvatarResolver; import org.sonar.server.issue.AvatarResolverImpl; import org.sonar.server.issue.FakeAvatarResolver; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestRequest; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.SearchUsersResponse; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.server.ws.WebService.Param.PAGE; import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE; import static org.sonar.api.server.ws.WebService.Param.SELECTED; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.MediaTypes.JSON; public class SearchUsersActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final QualityGatesWsSupport wsSupport = new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)); private AvatarResolver avatarResolver = new FakeAvatarResolver(); private WsActionTester ws = new WsActionTester(new SearchUsersAction(db.getDbClient(), wsSupport, avatarResolver)); @Test public void test_definition() { WebService.Action def = ws.getDef(); assertThat(def.key()).isEqualTo("search_users"); assertThat(def.isPost()).isFalse(); assertThat(def.params()).extracting(WebService.Param::key) .containsExactlyInAnyOrder("gateName", "selected", "q", "p", "ps"); } @Test public void test_example() { avatarResolver = new AvatarResolverImpl(); ws = new WsActionTester(new SearchUsersAction(db.getDbClient(), wsSupport, avatarResolver)); QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(u -> u.setLogin("admin").setName("Administrator").setEmail("admin@email.com")); UserDto user2 = db.users().insertUser(u -> u.setLogin("george.orwell").setName("George Orwell").setEmail("george@orwell.com")); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); String result = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .setMediaType(JSON) .execute() .getInput(); assertJson(result).isSimilarTo(ws.getDef().responseExampleAsString()); } @Test public void search_all_users() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(u -> u.setEmail("user1@email.com")); UserDto user2 = db.users().insertUser(u -> u.setEmail("user2@email.com")); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()) .extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getAvatar, SearchUsersResponse.User::getSelected) .containsExactlyInAnyOrder( tuple(user1.getLogin(), user1.getName(), "user1@email.com_avatar", true), tuple(user2.getLogin(), user2.getName(), "user2@email.com_avatar", false)); } @Test public void search_selected_users() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "selected") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getSelected) .containsExactlyInAnyOrder( tuple(user1.getLogin(), user1.getName(), true)); } @Test public void search_deselected_users() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "deselected") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::getName, SearchUsersResponse.User::getSelected) .containsExactlyInAnyOrder( tuple(user2.getLogin(), user2.getName(), false)); } @Test public void search_by_login() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(); UserDto user2 = db.users().insertUser(); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(TEXT_QUERY, user1.getLogin()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin) .containsExactlyInAnyOrder(user1.getLogin()); } @Test public void search_by_name() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(u -> u.setName("John Doe")); UserDto user2 = db.users().insertUser(u -> u.setName("Jane Doe")); UserDto user3 = db.users().insertUser(u -> u.setName("John Smith")); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(TEXT_QUERY, "ohn") .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin) .containsExactlyInAnyOrder(user1.getLogin(), user3.getLogin()); } @Test public void user_without_email() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(u -> u.setEmail(null)); db.qualityGates().addUserPermission(gate, user); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin, SearchUsersResponse.User::hasAvatar) .containsExactlyInAnyOrder(tuple(user.getLogin(), false)); } @Test public void paging_search() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user2 = db.users().insertUser(u -> u.setName("user2")); UserDto user3 = db.users().insertUser(u -> u.setName("user3")); UserDto user1 = db.users().insertUser(u -> u.setName("user1")); db.qualityGates().addUserPermission(gate, user1); db.qualityGates().addUserPermission(gate, user2); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .setParam(PAGE, "1") .setParam(PAGE_SIZE, "1") .executeProtobuf(SearchUsersResponse.class).getUsersList()) .extracting(SearchUsersResponse.User::getLogin) .containsExactly(user1.getLogin()); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .setParam(PAGE, "3") .setParam(PAGE_SIZE, "1") .executeProtobuf(SearchUsersResponse.class).getUsersList()) .extracting(SearchUsersResponse.User::getLogin) .containsExactly(user3.getLogin()); assertThat(ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .setParam(PAGE, "1") .setParam(PAGE_SIZE, "10") .executeProtobuf(SearchUsersResponse.class).getUsersList()) .extracting(SearchUsersResponse.User::getLogin) .containsExactly(user1.getLogin(), user2.getLogin(), user3.getLogin()); } @Test public void uses_global_permission() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user1 = db.users().insertUser(); db.qualityGates().addUserPermission(gate, user1); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user1.getLogin()); } @Test public void qp_administers_can_search_users() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user.getLogin()); } @Test public void qp_editors_can_search_users() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); UserDto userAllowedToEditProfile = db.users().insertUser(); db.qualityGates().addUserPermission(gate, userAllowedToEditProfile); userSession.logIn(userAllowedToEditProfile); SearchUsersResponse response = ws.newRequest() .setParam(PARAM_GATE_NAME, gate.getName()) .setParam(SELECTED, "all") .executeProtobuf(SearchUsersResponse.class); assertThat(response.getUsersList()).extracting(SearchUsersResponse.User::getLogin).containsExactlyInAnyOrder(user.getLogin(), userAllowedToEditProfile.getLogin()); } @Test public void fail_when_quality_gate_does_not_exist() { UserDto user = db.users().insertUser(); userSession.logIn().addPermission(ADMINISTER_QUALITY_GATES); TestRequest request = ws.newRequest().setParam(PARAM_GATE_NAME, "unknown"); assertThatThrownBy(request::execute) .isInstanceOf(NotFoundException.class) .hasMessage("No quality gate has been found for name unknown"); } @Test public void fail_when_not_enough_permission() { QualityGateDto gate = db.qualityGates().insertQualityGate(); UserDto user = db.users().insertUser(); userSession.logIn(db.users().insertUser()); TestRequest request = ws.newRequest().setParam(PARAM_GATE_NAME, gate.getName()); assertThatThrownBy(request::execute) .isInstanceOf(ForbiddenException.class); } }
12,901
40.88961
167
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/SelectActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.ComponentDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.web.UserRole.ADMIN; import static org.sonar.api.web.UserRole.ISSUE_ADMIN; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_GATE_NAME; public class SelectActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final ComponentFinder componentFinder = TestComponentFinder.from(db); private final SelectAction underTest = new SelectAction(dbClient, new QualityGatesWsSupport(db.getDbClient(), userSession, componentFinder)); private final WsActionTester ws = new WsActionTester(underTest); @Test public void select_by_key() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); assertSelected(qualityGate, project); } @Test public void change_quality_gate_for_project() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto initialQualityGate = db.qualityGates().insertQualityGate(); QualityGateDto secondQualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ws.newRequest() .setParam(PARAM_GATE_NAME, initialQualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); ws.newRequest() .setParam(PARAM_GATE_NAME, secondQualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); assertSelected(secondQualityGate, project); } @Test public void select_same_quality_gate_for_project_twice() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto initialQualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ws.newRequest() .setParam(PARAM_GATE_NAME, initialQualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); ws.newRequest() .setParam(PARAM_GATE_NAME, initialQualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); assertSelected(initialQualityGate, project); } @Test public void project_admin() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); userSession.logIn().addProjectPermission(ADMIN, project); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); assertSelected(qualityGate, project); } @Test public void gate_administrator_can_associate_a_gate_to_a_project() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute(); assertSelected(qualityGate, project); } @Test public void fail_when_no_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, "unknown") .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_no_project_key() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", "unknown") .execute()) .isInstanceOf(NotFoundException.class); } @Test public void fail_when_anonymous() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.anonymous(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_not_project_admin() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn().addProjectPermission(ISSUE_ADMIN, project); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } @Test public void fail_when_not_quality_gates_admin() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent(); userSession.logIn(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_GATE_NAME, qualityGate.getName()) .setParam("projectKey", project.getKey()) .execute()) .isInstanceOf(ForbiddenException.class); } private void assertSelected(QualityGateDto qualityGate, ProjectDto project) { Optional<String> qGateUuid = db.qualityGates().selectQGateUuidByProjectUuid(project.getUuid()); assertThat(qGateUuid) .isNotNull() .isNotEmpty() .hasValue(qualityGate.getUuid()); } }
7,602
35.204762
99
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/SetAsDefaultActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbTester; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_NAME; public class SetAsDefaultActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final WsActionTester ws = new WsActionTester( new SetAsDefaultAction(db.getDbClient(), userSession, new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)))); @Test public void verify_definition() { WebService.Action action = ws.getDef(); assertThat(action.key()).isEqualTo("set_as_default"); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.changelog()).isNotEmpty(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("name", true)); } @Test public void set_default() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("name")); ws.newRequest() .setParam(PARAM_NAME, "name") .execute(); assertThat(db.getDbClient().propertiesDao().selectGlobalProperty(db.getSession(), "qualitygate.default").getValue()) .isEqualTo(qualityGate.getUuid()); } }
2,722
37.9
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/ShowActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateCaycChecker; import org.sonar.server.qualitygate.QualityGateFinder; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.ShowWsResponse; import org.sonarqube.ws.Qualitygates.ShowWsResponse.Condition; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.server.qualitygate.QualityGateCaycStatus.COMPLIANT; import static org.sonar.server.qualitygate.QualityGateCaycStatus.NON_COMPLIANT; import static org.sonar.test.JsonAssert.assertJson; import static org.sonarqube.ws.Qualitygates.Actions; public class ShowActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final QualityGateCaycChecker qualityGateCaycChecker = mock(QualityGateCaycChecker.class); private final WsActionTester ws = new WsActionTester( new ShowAction(db.getDbClient(), new QualityGateFinder(db.getDbClient()), new QualityGatesWsSupport(db.getDbClient(), userSession, TestComponentFinder.from(db)), qualityGateCaycChecker)); @Before public void setUp() { when(qualityGateCaycChecker.checkCaycCompliant(any(), any())).thenReturn(COMPLIANT); } @Test public void show() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); MetricDto metric1 = db.measures().insertMetric(); MetricDto metric2 = db.measures().insertMetric(); QualityGateConditionDto condition1 = db.qualityGates().addCondition(qualityGate, metric1, c -> c.setOperator("GT")); QualityGateConditionDto condition2 = db.qualityGates().addCondition(qualityGate, metric2, c -> c.setOperator("LT")); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getName()).isEqualTo(qualityGate.getName()); assertThat(response.getIsBuiltIn()).isFalse(); assertThat(response.getConditionsList()).hasSize(2); assertThat(response.getConditionsList()) .extracting(Condition::getId, Condition::getMetric, Condition::getOp, Condition::getError) .containsExactlyInAnyOrder( tuple(condition1.getUuid(), metric1.getKey(), "GT", condition1.getErrorThreshold()), tuple(condition2.getUuid(), metric2.getKey(), "LT", condition2.getErrorThreshold())); } @Test public void show_built_in() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getIsBuiltIn()).isTrue(); } @Test public void show_isCaycCompliant() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); when(qualityGateCaycChecker.checkCaycCompliant(any(DbSession.class), eq(qualityGate.getUuid()))).thenReturn(COMPLIANT); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertEquals(COMPLIANT.toString(), response.getCaycStatus()); } @Test public void show_by_name() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getName()).isEqualTo(qualityGate.getName()); } @Test public void no_condition() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getName()).isEqualTo(qualityGate.getName()); assertThat(response.getConditionsList()).isEmpty(); } @Test public void actions() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate2); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); Actions actions = response.getActions(); assertThat(actions.getRename()).isTrue(); assertThat(actions.getManageConditions()).isTrue(); assertThat(actions.getDelete()).isTrue(); assertThat(actions.getCopy()).isTrue(); assertThat(actions.getSetAsDefault()).isTrue(); assertThat(actions.getAssociateProjects()).isTrue(); } @Test public void actions_on_default() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); Actions actions = response.getActions(); assertThat(actions.getRename()).isTrue(); assertThat(actions.getManageConditions()).isTrue(); assertThat(actions.getDelete()).isFalse(); assertThat(actions.getCopy()).isTrue(); assertThat(actions.getSetAsDefault()).isFalse(); assertThat(actions.getAssociateProjects()).isFalse(); } @Test public void actions_on_built_in() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(false)); db.qualityGates().setDefaultQualityGate(qualityGate2); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); Actions actions = response.getActions(); assertThat(actions.getRename()).isFalse(); assertThat(actions.getManageConditions()).isFalse(); assertThat(actions.getDelete()).isFalse(); assertThat(actions.getCopy()).isTrue(); assertThat(actions.getSetAsDefault()).isTrue(); assertThat(actions.getAssociateProjects()).isTrue(); } @Test public void actions_when_not_quality_gate_administer() { userSession.logIn("john").addPermission(ADMINISTER_QUALITY_PROFILES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); db.qualityGates().setDefaultQualityGate(qualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", qualityGate.getName()) .executeProtobuf(ShowWsResponse.class); Actions actions = response.getActions(); assertThat(actions.getRename()).isFalse(); assertThat(actions.getManageConditions()).isFalse(); assertThat(actions.getDelete()).isFalse(); assertThat(actions.getCopy()).isFalse(); assertThat(actions.getSetAsDefault()).isFalse(); assertThat(actions.getAssociateProjects()).isFalse(); } @Test public void actions_when_delegate_quality_gate_administer() { QualityGateDto defaultQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way")); QualityGateDto otherQualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("Sonar way - Without Coverage")); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(defaultQualityGate, user); db.qualityGates().addUserPermission(otherQualityGate, user); userSession.logIn(user); db.qualityGates().setDefaultQualityGate(defaultQualityGate); ShowWsResponse response = ws.newRequest() .setParam("name", defaultQualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getActions()) .extracting( Actions::getRename, Actions::getDelete, Actions::getManageConditions, Actions::getCopy, Actions::getSetAsDefault, Actions::getAssociateProjects, Actions::getDelegate) .containsExactlyInAnyOrder( false, false, true, false, false, false, true); response = ws.newRequest() .setParam("name", otherQualityGate.getName()) .executeProtobuf(ShowWsResponse.class); assertThat(response.getActions()) .extracting( Actions::getRename, Actions::getDelete, Actions::getManageConditions, Actions::getCopy, Actions::getSetAsDefault, Actions::getAssociateProjects, Actions::getDelegate) .containsExactlyInAnyOrder( false, false, true, false, false, false, true); } @Test public void fail_when_no_name() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest().execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("The 'name' parameter is missing"); } @Test public void fail_when_condition_is_on_disabled_metric() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); db.qualityGates().setDefaultQualityGate(qualityGate); MetricDto metric = db.measures().insertMetric(); db.qualityGates().addCondition(qualityGate, metric); db.getDbClient().metricDao().disableByKey(db.getSession(), metric.getKey()); db.commit(); assertThatThrownBy(() -> ws.newRequest() .setParam("name", qualityGate.getName()) .execute()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining(format("Could not find metric with id %s", metric.getUuid())); } @Test public void fail_when_quality_name_does_not_exist() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); assertThatThrownBy(() -> ws.newRequest() .setParam("name", "UNKNOWN") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate has been found for name UNKNOWN"); } @Test public void json_example() { userSession.logIn("admin").addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setName("My Quality Gate")); QualityGateDto qualityGate2 = db.qualityGates().insertQualityGate(qg -> qg.setName("My Quality Gate 2")); db.qualityGates().setDefaultQualityGate(qualityGate2); MetricDto blockerViolationsMetric = db.measures().insertMetric(m -> m.setKey("blocker_violations")); MetricDto criticalViolationsMetric = db.measures().insertMetric(m -> m.setKey("tests")); db.qualityGates().addCondition(qualityGate, blockerViolationsMetric, c -> c.setOperator("GT").setErrorThreshold("0")); db.qualityGates().addCondition(qualityGate, criticalViolationsMetric, c -> c.setOperator("LT").setErrorThreshold("10")); when(qualityGateCaycChecker.checkCaycCompliant(any(), any())).thenReturn(NON_COMPLIANT); String response = ws.newRequest() .setParam("name", qualityGate.getName()) .execute() .getInput(); assertJson(response).ignoreFields("id") .isSimilarTo(getClass().getResource("show-example.json")); } @Test public void verify_definition() { WebService.Action action = ws.getDef(); assertThat(action.since()).isEqualTo("4.3"); assertThat(action.params()) .extracting(Param::key, Param::isRequired) .containsExactlyInAnyOrder( tuple("name", true)); } }
13,655
40.634146
124
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualitygate/ws/UpdateConditionActionIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualitygate.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.TestComponentFinder; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualitygate.QualityGateConditionsUpdater; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import org.sonarqube.ws.Qualitygates.CreateConditionResponse; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_GATES; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ERROR; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_ID; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_METRIC; import static org.sonar.server.qualitygate.ws.QualityGatesWsParameters.PARAM_OPERATOR; @RunWith(DataProviderRunner.class) public class UpdateConditionActionIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); private final DbClient dbClient = db.getDbClient(); private final DbSession dbSession = db.getSession(); private final UpdateConditionAction underTest = new UpdateConditionAction(dbClient, new QualityGateConditionsUpdater(dbClient), new QualityGatesWsSupport(dbClient, userSession, TestComponentFinder.from(db))); private final WsActionTester ws = new WsActionTester(underTest); @Test public void update_error_condition() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("GT").setErrorThreshold("80")); ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute(); assertCondition(qualityGate, metric, "LT", "90"); } @Test public void test_response() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("GT").setErrorThreshold("80")); CreateConditionResponse response = ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "45") .executeProtobuf(CreateConditionResponse.class); assertThat(response.getId()).isEqualTo(condition.getUuid()); assertThat(response.getMetric()).isEqualTo(metric.getKey()); assertThat(response.getOp()).isEqualTo("LT"); assertThat(response.getError()).isEqualTo("45"); } @Test public void user_with_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); UserDto user = db.users().insertUser(); db.qualityGates().addUserPermission(qualityGate, user); userSession.logIn(user); TestResponse response = ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "45") .execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void user_with_group_permission_can_call_endpoint() { QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); UserDto user = db.users().insertUser(); GroupDto group = db.users().insertGroup(); db.qualityGates().addGroupPermission(qualityGate, group); userSession.logIn(user).setGroups(group); TestResponse response = ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "45") .execute(); assertThat(response.getStatus()).isEqualTo(200); } @Test public void fail_to_update_built_in_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(qg -> qg.setBuiltIn(true)); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "10") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(format("Operation forbidden for built-in Quality Gate '%s'", qualityGate.getName())); } @Test public void fail_on_unknown_condition() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, "123") .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(NotFoundException.class) .hasMessageContaining("No quality gate condition with uuid '123'"); } @Test public void fail_when_condition_match_unknown_quality_gate() { userSession.addPermission(ADMINISTER_QUALITY_GATES); MetricDto metric = insertMetric(); QualityGateConditionDto condition = new QualityGateConditionDto().setUuid("uuid") .setMetricUuid("metric") .setQualityGateUuid("123"); db.getDbClient().gateConditionDao().insert(condition, dbSession); db.commit(); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining(format("Condition '%s' is linked to an unknown quality gate '%s'", condition.getUuid(), 123L)); } @Test public void fail_with_unknown_operator() { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(0)); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator("LT").setErrorThreshold("80")); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "ABC") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Value of parameter 'op' (ABC) must be one of: [LT, GT]"); } @Test @UseDataProvider("update_invalid_operators_and_direction") public void fail_with_invalid_operators_for_direction(String validOperator, String updateOperator, int direction) { userSession.addPermission(ADMINISTER_QUALITY_GATES); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(direction)); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric, c -> c.setOperator(validOperator).setErrorThreshold("80")); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, updateOperator) .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(BadRequestException.class) .hasMessageContaining(format("Operator %s is not allowed for this metric.", updateOperator)); } @Test public void throw_ForbiddenException_if_not_gate_administrator() { userSession.logIn(); QualityGateDto qualityGate = db.qualityGates().insertQualityGate(); MetricDto metric = insertMetric(); QualityGateConditionDto condition = db.qualityGates().addCondition(qualityGate, metric); assertThatThrownBy(() -> ws.newRequest() .setParam(PARAM_ID, condition.getUuid()) .setParam(PARAM_METRIC, metric.getKey()) .setParam(PARAM_OPERATOR, "LT") .setParam(PARAM_ERROR, "90") .execute()) .isInstanceOf(ForbiddenException.class) .hasMessageContaining("Insufficient privileges"); } @Test public void test_ws_definition() { WebService.Action action = ws.getDef(); assertThat(action).isNotNull(); assertThat(action.isInternal()).isFalse(); assertThat(action.isPost()).isTrue(); assertThat(action.responseExampleAsString()).isNull(); assertThat(action.params()) .extracting(WebService.Param::key, WebService.Param::isRequired) .containsExactlyInAnyOrder( tuple("id", true), tuple("metric", true), tuple("error", true), tuple("op", false)); } @DataProvider public static Object[][] update_invalid_operators_and_direction() { return new Object[][]{ {"GT", "LT", -1}, {"LT", "GT", 1}, }; } private void assertCondition(QualityGateDto qualityGate, MetricDto metric, String operator, String error) { assertThat(dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGate.getUuid())) .extracting(QualityGateConditionDto::getQualityGateUuid, QualityGateConditionDto::getMetricUuid, QualityGateConditionDto::getOperator, QualityGateConditionDto::getErrorThreshold) .containsExactlyInAnyOrder(tuple(qualityGate.getUuid(), metric.getUuid(), operator, error)); } private MetricDto insertMetric() { return db.measures().insertMetric(m -> m.setValueType(INT.name()).setHidden(false).setDirection(0)); } }
12,225
40.444068
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileBackuperImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import com.google.common.io.Resources; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.qualityprofile.builtin.QProfileName; import org.sonar.server.rule.RuleCreator; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection; public class QProfileBackuperImplIT { private static final String EMPTY_BACKUP = "<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules/>" + "</profile>"; private final System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); private final DummyReset reset = new DummyReset(); private final QProfileFactory profileFactory = new DummyProfileFactory(); private final RuleCreator ruleCreator = mock(RuleCreator.class); private final QProfileBackuper underTest = new QProfileBackuperImpl(db.getDbClient(), reset, profileFactory, ruleCreator, new QProfileParser()); @Test public void backup_generates_xml_file() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(profile, rule); StringWriter writer = new StringWriter(); underTest.backup(db.getSession(), profile, writer); assertThat(writer).hasToString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<profile><name>" + profile.getName() + "</name>" + "<language>" + profile.getLanguage() + "</language>" + "<rules>" + "<rule>" + "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" + "<key>" + rule.getRuleKey() + "</key>" + "<type>" + RuleType.valueOf(rule.getType()).name() + "</type>" + "<priority>" + activeRule.getSeverityString() + "</priority>" + "<parameters></parameters>" + "</rule>" + "</rules>" + "</profile>"); } @Test public void backup_rules_having_parameters() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto profile = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(profile, rule, param); StringWriter writer = new StringWriter(); underTest.backup(db.getSession(), profile, writer); assertThat(writer.toString()).contains( "<rule>" + "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" + "<key>" + rule.getRuleKey() + "</key>" + "<type>" + RuleType.valueOf(rule.getType()).name() + "</type>" + "<priority>" + activeRule.getSeverityString() + "</priority>" + "<parameters><parameter>" + "<key>" + param.getName() + "</key>" + "<value>20</value>" + "</parameter></parameters>" + "</rule>"); } @Test public void backup_empty_profile() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule.getLanguage()); StringWriter writer = new StringWriter(); underTest.backup(db.getSession(), profile, writer); assertThat(writer).hasToString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<profile><name>" + profile.getName() + "</name>" + "<language>" + profile.getLanguage() + "</language>" + "<rules></rules>" + "</profile>"); } @Test public void backup_custom_rules_with_params() { RuleDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto .setIsTemplate(true)); RuleDto rule = db.rules().insert( newRule(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) .setName("custom rule name") .setStatus(RuleStatus.READY) .setTemplateUuid(templateRule.getUuid())); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto profile = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(profile, rule, param); StringWriter writer = new StringWriter(); underTest.backup(db.getSession(), profile, writer); assertThat(writer).hasToString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<profile>" + "<name>" + profile.getName() + "</name>" + "<language>" + profile.getLanguage() + "</language>" + "<rules><rule>" + "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" + "<key>" + rule.getKey().rule() + "</key>" + "<type>" + RuleType.valueOf(rule.getType()) + "</type>" + "<priority>" + activeRule.getSeverityString() + "</priority>" + "<name>" + rule.getName() + "</name>" + "<templateKey>" + templateRule.getKey().rule() + "</templateKey>" + "<description>" + rule.getDefaultRuleDescriptionSection().getContent() + "</description>" + "<parameters><parameter>" + "<key>" + param.getName() + "</key>" + "<value>20</value>" + "</parameter></parameters>" + "</rule></rules></profile>"); } @Test public void backup_custom_rules_without_description_section() { var rule = newRuleWithoutDescriptionSection(); db.rules().insert(rule); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto profile = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(profile, rule, param); StringWriter writer = new StringWriter(); underTest.backup(db.getSession(), profile, writer); assertThat(writer).hasToString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<profile>" + "<name>" + profile.getName() + "</name>" + "<language>" + profile.getLanguage() + "</language>" + "<rules><rule>" + "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" + "<key>" + rule.getKey().rule() + "</key>" + "<type>" + RuleType.valueOf(rule.getType()) + "</type>" + "<priority>" + activeRule.getSeverityString() + "</priority>" + "<parameters><parameter>" + "<key>" + param.getName() + "</key>" + "<value>20</value>" + "</parameter></parameters>" + "</rule></rules></profile>"); } @Test public void restore_backup_on_the_profile_specified_in_backup() { Reader backup = new StringReader(EMPTY_BACKUP); QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, (String) null); assertThat(summary.profile().getName()).isEqualTo("foo"); assertThat(summary.profile().getLanguage()).isEqualTo("js"); assertThat(reset.calledProfile.getKee()).isEqualTo(summary.profile().getKee()); assertThat(reset.calledActivations).isEmpty(); } @Test public void restore_detects_deprecated_rule_keys() { String ruleUuid = db.rules().insert(RuleKey.of("sonarjs", "s001")).getUuid(); db.rules().insertDeprecatedKey(c -> c.setRuleUuid(ruleUuid).setOldRuleKey("oldkey").setOldRepositoryKey("oldrepo")); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules>" + "<rule>" + "<repositoryKey>oldrepo</repositoryKey>" + "<key>oldkey</key>" + "<priority>BLOCKER</priority>" + "<parameters>" + "<parameter><key>bar</key><value>baz</value></parameter>" + "</parameters>" + "</rule>" + "</rules>" + "</profile>"); underTest.restore(db.getSession(), backup, (String) null); assertThat(reset.calledActivations).hasSize(1); RuleActivation activation = reset.calledActivations.get(0); assertThat(activation.getSeverity()).isEqualTo("BLOCKER"); assertThat(activation.getRuleUuid()).isEqualTo(ruleUuid); assertThat(activation.getParameter("bar")).isEqualTo("baz"); } @Test public void restore_ignores_deprecated_rule_keys_if_new_key_is_already_present() { String ruleUuid = db.rules().insert(RuleKey.of("sonarjs", "s001")).getUuid(); db.rules().insertDeprecatedKey(c -> c.setRuleUuid(ruleUuid).setOldRuleKey("oldkey").setOldRepositoryKey("oldrepo")); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules>" + "<rule>" + "<repositoryKey>oldrepo</repositoryKey>" + "<key>oldkey</key>" + "<priority>MAJOR</priority>" + "<parameters>" + "<parameter><key>bar</key><value>baz</value></parameter>" + "</parameters>" + "</rule>" + "<rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s001</key>" + "<priority>BLOCKER</priority>" + "<parameters>" + "<parameter><key>bar2</key><value>baz2</value></parameter>" + "</parameters>" + "</rule>" + "</rules>" + "</profile>"); underTest.restore(db.getSession(), backup, (String) null); assertThat(reset.calledActivations).hasSize(1); RuleActivation activation = reset.calledActivations.get(0); assertThat(activation.getSeverity()).isEqualTo("BLOCKER"); assertThat(activation.getRuleUuid()).isEqualTo(ruleUuid); assertThat(activation.getParameter("bar2")).isEqualTo("baz2"); } @Test public void restore_backup_on_profile_having_different_name() { Reader backup = new StringReader(EMPTY_BACKUP); QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, "bar"); assertThat(summary.profile().getName()).isEqualTo("bar"); assertThat(summary.profile().getLanguage()).isEqualTo("js"); assertThat(reset.calledProfile.getKee()).isEqualTo(summary.profile().getKee()); assertThat(reset.calledActivations).isEmpty(); } @Test public void restore_resets_the_activated_rules() { String ruleUuid = db.rules().insert(RuleKey.of("sonarjs", "s001")).getUuid(); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules>" + "<rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s001</key>" + "<priority>BLOCKER</priority>" + "<parameters>" + "<parameter><key>bar</key><value>baz</value></parameter>" + "</parameters>" + "</rule>" + "</rules>" + "</profile>"); underTest.restore(db.getSession(), backup, (String) null); assertThat(reset.calledActivations).hasSize(1); RuleActivation activation = reset.calledActivations.get(0); assertThat(activation.getSeverity()).isEqualTo("BLOCKER"); assertThat(activation.getRuleUuid()).isEqualTo(ruleUuid); assertThat(activation.getParameter("bar")).isEqualTo("baz"); } @Test public void restore_custom_rule() { when(ruleCreator.create(any(), anyList())).then(invocation -> Collections.singletonList(db.rules().insert(RuleKey.of("sonarjs", "s001")).getKey())); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile>" + "<name>custom rule</name>" + "<language>js</language>" + "<rules><rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s001</key>" + "<type>CODE_SMELL</type>" + "<priority>CRITICAL</priority>" + "<name>custom rule name</name>" + "<templateKey>rule_mc8</templateKey>" + "<description>custom rule description</description>" + "<parameters><parameter>" + "<key>bar</key>" + "<value>baz</value>" + "</parameter>" + "</parameters>" + "</rule></rules></profile>"); underTest.restore(db.getSession(), backup, (String) null); assertThat(reset.calledActivations).hasSize(1); RuleActivation activation = reset.calledActivations.get(0); assertThat(activation.getSeverity()).isEqualTo("CRITICAL"); assertThat(activation.getParameter("bar")).isEqualTo("baz"); } @Test public void restore_skips_rule_without_template_key_and_db_definition() { String ruleUuid = db.rules().insert(RuleKey.of("sonarjs", "s001")).getUuid(); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules>" + "<rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s001</key>" + "<priority>BLOCKER</priority>" + "<parameters>" + "<parameter><key>bar</key><value>baz</value></parameter>" + "</parameters>" + "</rule>" + "<rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s002</key>" + "<priority>MAJOR</priority>" + "</rule>" + "</rules>" + "</profile>"); underTest.restore(db.getSession(), backup, (String) null); assertThat(reset.calledActivations).hasSize(1); RuleActivation activation = reset.calledActivations.get(0); assertThat(activation.getRuleUuid()).isEqualTo(ruleUuid); assertThat(activation.getSeverity()).isEqualTo("BLOCKER"); assertThat(activation.getParameter("bar")).isEqualTo("baz"); } @Test public void copy_profile() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto from = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(from, rule, param); QProfileDto to = createProfile(rule.getLanguage()); underTest.copy(db.getSession(), from, to); assertThat(reset.calledActivations).extracting(RuleActivation::getRuleUuid).containsOnly(activeRule.getRuleUuid()); assertThat(reset.calledActivations.get(0).getParameter(param.getName())).isEqualTo("20"); assertThat(reset.calledProfile).isEqualTo(to); } @Test public void copy_profile_with_custom_rule() { RuleDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto .setIsTemplate(true)); RuleDto rule = db.rules().insert( newRule(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) .setName("custom rule name") .setStatus(RuleStatus.READY) .setTemplateUuid(templateRule.getUuid())); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto from = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(from, rule, param); QProfileDto to = createProfile(rule.getLanguage()); underTest.copy(db.getSession(), from, to); assertThat(reset.calledActivations).extracting(RuleActivation::getRuleUuid).containsOnly(activeRule.getRuleUuid()); assertThat(reset.calledActivations.get(0).getParameter(param.getName())).isEqualTo("20"); assertThat(reset.calledProfile).isEqualTo(to); } @Test public void fail_to_restore_if_bad_xml_format() { DbSession session = db.getSession(); StringReader backup = new StringReader("<rules><rule></rules>"); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> underTest.restore(session, backup, (String) null)); assertThat(thrown).hasMessage("Backup XML is not valid. Root element must be <profile>."); assertThat(reset.calledProfile).isNull(); } @Test public void fail_to_restore_if_not_xml_backup() { DbSession session = db.getSession(); StringReader backup = new StringReader("foo"); assertThrows(IllegalArgumentException.class, () -> underTest.restore(session, backup, (String) null)); assertThat(reset.calledProfile).isNull(); } @Test public void fail_to_restore_if_xml_is_not_well_formed() { assertThatThrownBy(() -> { String notWellFormedXml = "<?xml version='1.0' encoding='UTF-8'?><profile><name>\"profil\"</name><language>\"language\"</language><rules/></profile"; underTest.restore(db.getSession(), new StringReader(notWellFormedXml), (String) null); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Fail to restore Quality profile backup, XML document is not well formed"); } @Test public void fail_to_restore_if_duplicate_rule() throws Exception { DbSession session = db.getSession(); String xml = Resources.toString(getClass().getResource("QProfileBackuperIT/duplicates-xml-backup.xml"), UTF_8); StringReader backup = new StringReader(xml); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> underTest.restore(session, backup, (String) null)); assertThat(thrown).hasMessage("The quality profile cannot be restored as it contains duplicates for the following rules: xoo:x1, xoo:x2"); assertThat(reset.calledProfile).isNull(); } @Test public void fail_to_restore_external_rule() { db.rules().insert(RuleKey.of("sonarjs", "s001"), r -> r.setIsExternal(true)); Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" + "<profile><name>foo</name>" + "<language>js</language>" + "<rules>" + "<rule>" + "<repositoryKey>sonarjs</repositoryKey>" + "<key>s001</key>" + "<priority>BLOCKER</priority>" + "<parameters>" + "<parameter><key>bar</key><value>baz</value></parameter>" + "</parameters>" + "</rule>" + "</rules>" + "</profile>"); assertThatThrownBy(() -> { underTest.restore(db.getSession(), backup, (String) null); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The quality profile cannot be restored as it contains rules from external rule engines: sonarjs:s001"); } private RuleDto createRule() { return db.rules().insert(); } private QProfileDto createProfile(String language) { return db.qualityProfiles().insert(p -> p.setLanguage(language)); } private ActiveRuleDto activate(QProfileDto profile, RuleDto rule) { return db.qualityProfiles().activateRule(profile, rule); } private ActiveRuleDto activate(QProfileDto profile, RuleDto rule, RuleParamDto param) { ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile, rule); ActiveRuleParamDto dto = ActiveRuleParamDto.createFor(param) .setValue("20") .setActiveRuleUuid(activeRule.getUuid()); db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule, dto); return activeRule; } private static class DummyReset implements QProfileReset { private QProfileDto calledProfile; private List<RuleActivation> calledActivations; @Override public BulkChangeResult reset(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations) { this.calledProfile = profile; this.calledActivations = new ArrayList<>(activations); return new BulkChangeResult(); } } private static class DummyProfileFactory implements QProfileFactory { @Override public QProfileDto getOrCreateCustom(DbSession dbSession, QProfileName key) { return QualityProfileTesting.newQualityProfileDto() .setLanguage(key.getLanguage()) .setName(key.getName()); } @Override public QProfileDto checkAndCreateCustom(DbSession dbSession, QProfileName name) { throw new UnsupportedOperationException(); } @Override public QProfileDto createCustom(DbSession dbSession, QProfileName name, @Nullable String parentKey) { throw new UnsupportedOperationException(); } @Override public void delete(DbSession dbSession, Collection<QProfileDto> profiles) { throw new UnsupportedOperationException(); } } }
21,468
38.465074
155
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileComparisonIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import com.google.common.collect.ImmutableMap; import com.google.common.collect.MapDifference.ValueDifference; import org.assertj.core.data.MapEntry; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rule.Severity; import org.sonar.api.server.rule.RuleParamType; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.rule.RuleTesting; import org.sonar.server.es.EsTester; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.QProfileComparison.ActiveRuleDiff; import org.sonar.server.qualityprofile.QProfileComparison.QProfileComparisonResult; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.TypeValidations; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class QProfileComparisonIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone().anonymous(); @Rule public DbTester dbTester = DbTester.create(); @Rule public EsTester es = EsTester.create(); private DbSession dbSession; private QProfileRules qProfileRules; private QProfileComparison comparison; private RuleDto xooRule1; private RuleDto xooRule2; private QProfileDto left; private QProfileDto right; @Before public void before() { DbClient db = dbTester.getDbClient(); dbSession = db.openSession(false); RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE); ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db, es.client()); QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, db, new TypeValidations(singletonList(new IntegerTypeValidation())), userSession); qProfileRules = new QProfileRulesImpl(db, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService); comparison = new QProfileComparison(db); xooRule1 = RuleTesting.newXooX1().setSeverity("MINOR"); xooRule2 = RuleTesting.newXooX2().setSeverity("MAJOR"); db.ruleDao().insert(dbSession, xooRule1); db.ruleDao().insert(dbSession, xooRule2); db.ruleDao().insertRuleParam(dbSession, xooRule1, RuleParamDto.createFor(xooRule1) .setName("max").setType(RuleParamType.INTEGER.type())); db.ruleDao().insertRuleParam(dbSession, xooRule1, RuleParamDto.createFor(xooRule1) .setName("min").setType(RuleParamType.INTEGER.type())); left = QualityProfileTesting.newQualityProfileDto().setLanguage("xoo"); right = QualityProfileTesting.newQualityProfileDto().setLanguage("xoo"); db.qualityProfileDao().insert(dbSession, left, right); dbSession.commit(); } @After public void after() { dbSession.close(); } @Test public void compare_empty_profiles() { QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isEmpty(); assertThat(result.collectRuleKeys()).isEmpty(); } @Test public void compare_same() { RuleActivation commonActivation = RuleActivation.create(xooRule1.getUuid(), Severity.CRITICAL, ImmutableMap.of("min", "7", "max", "42")); qProfileRules.activateAndCommit(dbSession, left, singleton(commonActivation)); qProfileRules.activateAndCommit(dbSession, right, singleton(commonActivation)); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isEmpty(); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); } @Test public void compare_only_left() { RuleActivation activation = RuleActivation.create(xooRule1.getUuid()); qProfileRules.activateAndCommit(dbSession, left, singleton(activation)); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isEmpty(); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); } @Test public void compare_only_right() { qProfileRules.activateAndCommit(dbSession, right, singleton(RuleActivation.create(xooRule1.getUuid()))); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.modified()).isEmpty(); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); } @Test public void compare_disjoint() { qProfileRules.activateAndCommit(dbSession, left, singleton(RuleActivation.create(xooRule1.getUuid()))); qProfileRules.activateAndCommit(dbSession, right, singleton(RuleActivation.create(xooRule2.getUuid()))); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.inRight()).isNotEmpty().containsOnlyKeys(xooRule2.getKey()); assertThat(result.modified()).isEmpty(); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey(), xooRule2.getKey()); } @Test public void compare_modified_severity() { qProfileRules.activateAndCommit(dbSession, left, singleton(RuleActivation.create(xooRule1.getUuid(), Severity.CRITICAL, null))); qProfileRules.activateAndCommit(dbSession, right, singleton(RuleActivation.create(xooRule1.getUuid(), Severity.BLOCKER, null))); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); ActiveRuleDiff activeRuleDiff = result.modified().get(xooRule1.getKey()); assertThat(activeRuleDiff.leftSeverity()).isEqualTo(Severity.CRITICAL); assertThat(activeRuleDiff.rightSeverity()).isEqualTo(Severity.BLOCKER); assertThat(activeRuleDiff.paramDifference().areEqual()).isTrue(); } @Test public void compare_modified_param() { qProfileRules.activateAndCommit(dbSession, left, singleton(RuleActivation.create(xooRule1.getUuid(), null, ImmutableMap.of("max", "20")))); qProfileRules.activateAndCommit(dbSession, right, singleton(RuleActivation.create(xooRule1.getUuid(), null, ImmutableMap.of("max", "30")))); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); ActiveRuleDiff activeRuleDiff = result.modified().get(xooRule1.getKey()); assertThat(activeRuleDiff.leftSeverity()).isEqualTo(activeRuleDiff.rightSeverity()).isEqualTo(xooRule1.getSeverityString()); assertThat(activeRuleDiff.paramDifference().areEqual()).isFalse(); assertThat(activeRuleDiff.paramDifference().entriesDiffering()).isNotEmpty(); ValueDifference<String> paramDiff = activeRuleDiff.paramDifference().entriesDiffering().get("max"); assertThat(paramDiff.leftValue()).isEqualTo("20"); assertThat(paramDiff.rightValue()).isEqualTo("30"); } @Test public void compare_different_params() { qProfileRules.activateAndCommit(dbSession, left, singleton(RuleActivation.create(xooRule1.getUuid(), null, ImmutableMap.of("max", "20")))); qProfileRules.activateAndCommit(dbSession, right, singleton(RuleActivation.create(xooRule1.getUuid(), null, ImmutableMap.of("min", "5")))); QProfileComparisonResult result = comparison.compare(dbSession, left, right); assertThat(result.left().getKee()).isEqualTo(left.getKee()); assertThat(result.right().getKee()).isEqualTo(right.getKee()); assertThat(result.same()).isEmpty(); assertThat(result.inLeft()).isEmpty(); assertThat(result.inRight()).isEmpty(); assertThat(result.modified()).isNotEmpty().containsOnlyKeys(xooRule1.getKey()); assertThat(result.collectRuleKeys()).containsOnly(xooRule1.getKey()); ActiveRuleDiff activeRuleDiff = result.modified().get(xooRule1.getKey()); assertThat(activeRuleDiff.leftSeverity()).isEqualTo(activeRuleDiff.rightSeverity()).isEqualTo(xooRule1.getSeverityString()); assertThat(activeRuleDiff.paramDifference().areEqual()).isFalse(); assertThat(activeRuleDiff.paramDifference().entriesDiffering()).isEmpty(); assertThat(activeRuleDiff.paramDifference().entriesOnlyOnLeft()).containsExactly(MapEntry.entry("max", "20")); assertThat(activeRuleDiff.paramDifference().entriesOnlyOnRight()).containsExactly(MapEntry.entry("min", "5")); } }
11,854
47.586066
152
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileCopierIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.util.Collection; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; import org.sonar.server.qualityprofile.builtin.QProfileName; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; public class QProfileCopierIT { private static final String BACKUP = "<backup/>"; private final System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); @Rule public JUnitTempFolder temp = new JUnitTempFolder(); private final DummyProfileFactory profileFactory = new DummyProfileFactory(); private final QProfileBackuper backuper = mock(QProfileBackuper.class); private final QProfileCopier underTest = new QProfileCopier(db.getDbClient(), profileFactory, backuper); @Test public void create_target_profile_and_copy_rules() { QProfileDto source = db.qualityProfiles().insert(); QProfileDto target = underTest.copyToName(db.getSession(), source, "foo"); assertThat(target.getLanguage()).isEqualTo(source.getLanguage()); assertThat(target.getName()).isEqualTo("foo"); assertThat(target.getParentKee()).isNull(); verify(backuper).copy(db.getSession(), source, target); } @Test public void create_target_profile_with_same_parent_than_source_profile() { QProfileDto parent = db.qualityProfiles().insert(); QProfileDto source = db.qualityProfiles().insert(p -> p.setParentKee(parent.getKee())); QProfileDto target = underTest.copyToName(db.getSession(), source, "foo"); assertThat(target.getLanguage()).isEqualTo(source.getLanguage()); assertThat(target.getName()).isEqualTo("foo"); assertThat(target.getParentKee()).isEqualTo(parent.getKee()); verify(backuper).copy(db.getSession(), source, target); } @Test public void fail_to_copy_on_self() { QProfileDto source = db.qualityProfiles().insert(); try { underTest.copyToName(db.getSession(), source, source.getName()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Source and target profiles are equal: " + source.getName()); verifyNoInteractions(backuper); } } @Test public void copy_to_existing_profile() { QProfileDto profile1 = db.qualityProfiles().insert(); QProfileDto profile2 = db.qualityProfiles().insert(p -> p.setLanguage(profile1.getLanguage())); QProfileDto target = underTest.copyToName(db.getSession(), profile1, profile2.getName()); assertThat(profileFactory.createdProfile).isNull(); assertThat(target.getLanguage()).isEqualTo(profile2.getLanguage()); assertThat(target.getName()).isEqualTo(profile2.getName()); verify(backuper).copy(eq(db.getSession()), eq(profile1), argThat(a -> a.getKee().equals(profile2.getKee()))); } private static class DummyProfileFactory implements QProfileFactory { private QProfileDto createdProfile; @Override public QProfileDto getOrCreateCustom(DbSession dbSession, QProfileName key) { throw new UnsupportedOperationException(); } @Override public QProfileDto checkAndCreateCustom(DbSession dbSession, QProfileName key) { throw new UnsupportedOperationException(); } @Override public QProfileDto createCustom(DbSession dbSession, QProfileName key, @Nullable String parentKey) { createdProfile = QualityProfileTesting.newQualityProfileDto() .setLanguage(key.getLanguage()) .setParentKee(parentKey) .setName(key.getName()); return createdProfile; } @Override public void delete(DbSession dbSession, Collection<QProfileDto> profiles) { throw new UnsupportedOperationException(); } } }
5,139
35.978417
113
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileExportersIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.profiles.ProfileExporter; import org.sonar.api.profiles.ProfileImporter; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleFinder; import org.sonar.api.rules.RulePriority; import org.sonar.api.utils.System2; import org.sonar.api.utils.ValidationMessages; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.rule.DefaultRuleFinder; import org.sonar.server.rule.RuleDescriptionFormatter; import org.sonar.server.tester.UserSessionRule; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.toInputStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto; public class QProfileExportersIT { @org.junit.Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); private final System2 system2 = new AlwaysIncreasingSystem2(); @org.junit.Rule public DbTester db = DbTester.create(system2); private final RuleFinder ruleFinder = new DefaultRuleFinder(db.getDbClient(), mock(RuleDescriptionFormatter.class)); private final ProfileExporter[] exporters = new ProfileExporter[] { new StandardExporter(), new XooExporter()}; private final ProfileImporter[] importers = new ProfileImporter[] { new XooProfileImporter(), new XooProfileImporterWithMessages(), new XooProfileImporterWithError()}; private RuleDto rule; private final QProfileRules qProfileRules = mock(QProfileRules.class); private final QProfileExporters underTest = new QProfileExporters(db.getDbClient(), ruleFinder, qProfileRules, exporters, importers); @Before public void setUp() { rule = db.rules().insert(r -> r.setLanguage("xoo").setRepositoryKey("SonarXoo").setRuleKey("R1")); } @Test public void exportersForLanguage() { assertThat(underTest.exportersForLanguage("xoo")).hasSize(2); assertThat(underTest.exportersForLanguage("java")).hasSize(1); assertThat(underTest.exportersForLanguage("java").get(0)).isInstanceOf(StandardExporter.class); } @Test public void mimeType() { assertThat(underTest.mimeType("xootool")).isEqualTo("plain/custom"); // default mime type assertThat(underTest.mimeType("standard")).isEqualTo("text/plain"); } @Test public void import_xml() { QProfileDto profile = createProfile(); underTest.importXml(profile, "XooProfileImporter", toInputStream("<xml/>", UTF_8), db.getSession()); ArgumentCaptor<QProfileDto> profileCapture = ArgumentCaptor.forClass(QProfileDto.class); Class<Collection<RuleActivation>> collectionClass = (Class<Collection<RuleActivation>>) (Class) Collection.class; ArgumentCaptor<Collection<RuleActivation>> activationCapture = ArgumentCaptor.forClass(collectionClass); verify(qProfileRules).activateAndCommit(any(DbSession.class), profileCapture.capture(), activationCapture.capture()); assertThat(profileCapture.getValue().getKee()).isEqualTo(profile.getKee()); Collection<RuleActivation> activations = activationCapture.getValue(); assertThat(activations).hasSize(1); RuleActivation activation = activations.iterator().next(); assertThat(activation.getRuleUuid()).isEqualTo(rule.getUuid()); assertThat(activation.getSeverity()).isEqualTo("CRITICAL"); } @Test public void import_xml_return_messages() { QProfileDto profile = createProfile(); QProfileResult result = underTest.importXml(profile, "XooProfileImporterWithMessages", toInputStream("<xml/>", UTF_8), db.getSession()); assertThat(result.infos()).containsOnly("an info"); assertThat(result.warnings()).containsOnly("a warning"); } @Test public void fail_to_import_xml_when_error_in_importer() { QProfileDto qProfileDto = newQualityProfileDto(); InputStream inputStream = toInputStream("<xml/>", UTF_8); DbSession dbSession = db.getSession(); assertThatThrownBy(() -> underTest.importXml( qProfileDto, "XooProfileImporterWithError", inputStream, dbSession)) .isInstanceOf(BadRequestException.class) .hasMessage("error!"); } @Test public void fail_to_import_xml_on_unknown_importer() { QProfileDto qProfileDto = newQualityProfileDto(); InputStream inputStream = toInputStream("<xml/>", UTF_8); DbSession dbSession = db.getSession(); assertThatThrownBy(() -> underTest.importXml(qProfileDto, "Unknown", inputStream, dbSession)) .isInstanceOf(BadRequestException.class) .hasMessage("No such importer : Unknown"); } @Test public void export_empty_profile() { QProfileDto profile = createProfile(); StringWriter writer = new StringWriter(); underTest.export(db.getSession(), profile, "standard", writer); assertThat(writer).hasToString("standard -> " + profile.getName() + " -> 0"); writer = new StringWriter(); underTest.export(db.getSession(), profile, "xootool", writer); assertThat(writer).hasToString("xoo -> " + profile.getName() + " -> 0"); } @Test public void export_profile() { QProfileDto profile = createProfile(); db.qualityProfiles().activateRule(profile, rule); StringWriter writer = new StringWriter(); underTest.export(db.getSession(), profile, "standard", writer); assertThat(writer).hasToString("standard -> " + profile.getName() + " -> 1"); writer = new StringWriter(); underTest.export(db.getSession(), profile, "xootool", writer); assertThat(writer).hasToString("xoo -> " + profile.getName() + " -> 1"); } @Test public void export_throws_NotFoundException_if_exporter_does_not_exist() { QProfileDto profile = createProfile(); assertThatThrownBy(() -> { underTest.export(db.getSession(), profile, "does_not_exist", new StringWriter()); }) .isInstanceOf(NotFoundException.class) .hasMessage("Unknown quality profile exporter: does_not_exist"); } private QProfileDto createProfile() { return db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage())); } public static class XooExporter extends ProfileExporter { public XooExporter() { super("xootool", "Xoo Tool"); } @Override public String[] getSupportedLanguages() { return new String[] {"xoo"}; } @Override public String getMimeType() { return "plain/custom"; } @Override public void exportProfile(RulesProfile profile, Writer writer) { try { writer.write("xoo -> " + profile.getName() + " -> " + profile.getActiveRules().size()); } catch (IOException e) { throw new IllegalStateException(e); } } } public static class StandardExporter extends ProfileExporter { public StandardExporter() { super("standard", "Standard"); } @Override public void exportProfile(RulesProfile profile, Writer writer) { try { writer.write("standard -> " + profile.getName() + " -> " + profile.getActiveRules().size()); } catch (IOException e) { throw new IllegalStateException(e); } } } public class XooProfileImporter extends ProfileImporter { public XooProfileImporter() { super("XooProfileImporter", "Xoo Profile Importer"); } @Override public String[] getSupportedLanguages() { return new String[] {"xoo"}; } @Override public RulesProfile importProfile(Reader reader, ValidationMessages messages) { RulesProfile rulesProfile = RulesProfile.create(); rulesProfile.activateRule(Rule.create(rule.getRepositoryKey(), rule.getRuleKey()), RulePriority.CRITICAL); return rulesProfile; } } public static class XooProfileImporterWithMessages extends ProfileImporter { public XooProfileImporterWithMessages() { super("XooProfileImporterWithMessages", "Xoo Profile Importer With Message"); } @Override public String[] getSupportedLanguages() { return new String[] {}; } @Override public RulesProfile importProfile(Reader reader, ValidationMessages messages) { messages.addWarningText("a warning"); messages.addInfoText("an info"); return RulesProfile.create(); } } public static class XooProfileImporterWithError extends ProfileImporter { public XooProfileImporterWithError() { super("XooProfileImporterWithError", "Xoo Profile Importer With Error"); } @Override public RulesProfile importProfile(Reader reader, ValidationMessages messages) { messages.addErrorText("error!"); return RulesProfile.create(); } } }
10,193
35.537634
140
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileFactoryImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.util.Collection; import java.util.Collections; import org.assertj.core.api.AbstractObjectAssert; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.Uuids; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.project.ProjectDto; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgQProfileDto; import org.sonar.db.qualityprofile.QProfileChangeDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.RulesProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.qualityprofile.builtin.QProfileName; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; public class QProfileFactoryImplIT { private System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); private DbSession dbSession = db.getSession(); private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class); private QProfileFactory underTest = new QProfileFactoryImpl(db.getDbClient(), new SequenceUuidFactory(), system2, activeRuleIndexer); private RuleDto rule; private RuleParamDto ruleParam; @Before public void setUp() { rule = db.rules().insert(); ruleParam = db.rules().insertRuleParam(rule); } @Test public void checkAndCreateCustom() { QProfileDto profile = underTest.checkAndCreateCustom(dbSession, new QProfileName("xoo", "P1")); assertThat(profile.getKee()).isNotEmpty(); assertThat(profile.getName()).isEqualTo("P1"); assertThat(profile.getLanguage()).isEqualTo("xoo"); assertThat(profile.getRulesProfileUuid()).isNotNull(); assertThat(profile.isBuiltIn()).isFalse(); QProfileDto reloaded = db.getDbClient().qualityProfileDao().selectByNameAndLanguage(dbSession, profile.getName(), profile.getLanguage()); assertEqual(profile, reloaded); assertThat(db.getDbClient().qualityProfileDao().selectAll(dbSession)).extracting(QProfileDto::getKee).containsExactly(profile.getKee()); } @Test public void checkAndCreateCustom_throws_BadRequestException_if_name_null() { QProfileName name = new QProfileName("xoo", null); expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "quality_profiles.profile_name_cant_be_blank"); } @Test public void checkAndCreateCustom_throws_BadRequestException_if_name_empty() { QProfileName name = new QProfileName("xoo", ""); expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "quality_profiles.profile_name_cant_be_blank"); } @Test public void checkAndCreateCustom_throws_BadRequestException_if_already_exists() { QProfileName name = new QProfileName("xoo", "P1"); underTest.checkAndCreateCustom(dbSession, name); dbSession.commit(); expectBadRequestException(() -> underTest.checkAndCreateCustom(dbSession, name), "Quality profile already exists: xoo/P1"); } @Test public void delete_custom_profiles() { QProfileDto profile1 = createCustomProfile(); QProfileDto profile2 = createCustomProfile(); QProfileDto profile3 = createCustomProfile(); underTest.delete(dbSession, asList(profile1, profile2)); verifyCallActiveRuleIndexerDelete(profile1.getKee(), profile2.getKee()); assertThatCustomProfileDoesNotExist(profile1); assertThatCustomProfileDoesNotExist(profile2); assertThatCustomProfileExists(profile3); } @Test public void delete_removes_custom_profile_marked_as_default() { QProfileDto profile = createCustomProfile(); db.qualityProfiles().setAsDefault(profile); underTest.delete(dbSession, asList(profile)); assertThatCustomProfileDoesNotExist(profile); } @Test public void delete_removes_custom_profile_from_project_associations() { QProfileDto profile = createCustomProfile(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.qualityProfiles().associateWithProject(project, profile); underTest.delete(dbSession, asList(profile)); assertThatCustomProfileDoesNotExist(profile); } @Test public void delete_builtin_profile() { RulesProfileDto builtInProfile = createBuiltInProfile(); QProfileDto profile = associateBuiltInProfile(builtInProfile); underTest.delete(dbSession, asList(profile)); verifyNoCallsActiveRuleIndexerDelete(); // remove only from org_qprofiles assertThat(db.getDbClient().qualityProfileDao().selectAll(dbSession)).isEmpty(); assertThatRulesProfileExists(builtInProfile); } @Test public void delete_builtin_profile_associated_to_project() { RulesProfileDto builtInProfile = createBuiltInProfile(); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); QProfileDto profile = associateBuiltInProfile(builtInProfile); db.qualityProfiles().associateWithProject(project, profile); assertThat(db.getDbClient().qualityProfileDao().selectAssociatedToProjectAndLanguage(dbSession, project, profile.getLanguage())).isNotNull(); underTest.delete(dbSession, asList(profile)); verifyNoCallsActiveRuleIndexerDelete(); // remove only from org_qprofiles and project_qprofiles assertThat(db.getDbClient().qualityProfileDao().selectAll(dbSession)).isEmpty(); assertThat(db.getDbClient().qualityProfileDao().selectAssociatedToProjectAndLanguage(dbSession, project, profile.getLanguage())).isNull(); assertThatRulesProfileExists(builtInProfile); } @Test public void delete_builtin_profile_marked_as_default() { RulesProfileDto builtInProfile = createBuiltInProfile(); QProfileDto profile = associateBuiltInProfile(builtInProfile); db.qualityProfiles().setAsDefault(profile); underTest.delete(dbSession, asList(profile)); verifyNoCallsActiveRuleIndexerDelete(); // remove only from org_qprofiles and default_qprofiles assertThat(db.getDbClient().qualityProfileDao().selectAll(dbSession)).isEmpty(); assertThat(db.getDbClient().qualityProfileDao().selectDefaultProfile(dbSession, profile.getLanguage())).isNull(); assertThatRulesProfileExists(builtInProfile); } @Test public void delete_accepts_empty_list_of_keys() { QProfileDto profile = createCustomProfile(); underTest.delete(dbSession, Collections.emptyList()); verifyNoInteractions(activeRuleIndexer); assertQualityProfileFromDb(profile).isNotNull(); } @Test public void delete_removes_qprofile_edit_permissions() { QProfileDto profile = db.qualityProfiles().insert(); UserDto user = db.users().insertUser(); db.qualityProfiles().addUserPermission(profile, user); GroupDto group = db.users().insertGroup(); db.qualityProfiles().addGroupPermission(profile, group); underTest.delete(dbSession, asList(profile)); assertThat(db.countRowsOfTable(dbSession, "qprofile_edit_users")).isZero(); assertThat(db.countRowsOfTable(dbSession, "qprofile_edit_groups")).isZero(); } private QProfileDto createCustomProfile() { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("xoo").setIsBuiltIn(false)); ActiveRuleDto activeRuleDto = db.qualityProfiles().activateRule(profile, rule); ActiveRuleParamDto activeRuleParam = new ActiveRuleParamDto() .setRulesParameterUuid(ruleParam.getUuid()) .setKey("foo") .setValue("bar"); db.getDbClient().activeRuleDao().insertParam(dbSession, activeRuleDto, activeRuleParam); db.getDbClient().qProfileChangeDao().insert(dbSession, new QProfileChangeDto() .setChangeType(ActiveRuleChange.Type.ACTIVATED.name()) .setRulesProfileUuid(profile.getRulesProfileUuid())); db.commit(); return profile; } private RulesProfileDto createBuiltInProfile() { RulesProfileDto rulesProfileDto = new RulesProfileDto() .setIsBuiltIn(true) .setUuid(Uuids.createFast()) .setLanguage("xoo") .setName("Sonar way"); db.getDbClient().qualityProfileDao().insert(dbSession, rulesProfileDto); ActiveRuleDto activeRuleDto = new ActiveRuleDto() .setProfileUuid(rulesProfileDto.getUuid()) .setRuleUuid(rule.getUuid()) .setSeverity(Severity.BLOCKER); db.getDbClient().activeRuleDao().insert(dbSession, activeRuleDto); ActiveRuleParamDto activeRuleParam = new ActiveRuleParamDto() .setRulesParameterUuid(ruleParam.getUuid()) .setKey("foo") .setValue("bar"); db.getDbClient().activeRuleDao().insertParam(dbSession, activeRuleDto, activeRuleParam); db.getDbClient().qProfileChangeDao().insert(dbSession, new QProfileChangeDto() .setChangeType(ActiveRuleChange.Type.ACTIVATED.name()) .setRulesProfileUuid(rulesProfileDto.getUuid())); db.commit(); return rulesProfileDto; } private QProfileDto associateBuiltInProfile(RulesProfileDto rulesProfile) { OrgQProfileDto orgQProfileDto = new OrgQProfileDto() .setUuid(Uuids.createFast()) .setRulesProfileUuid(rulesProfile.getUuid()); db.getDbClient().qualityProfileDao().insert(dbSession, orgQProfileDto); db.commit(); return QProfileDto.from(orgQProfileDto, rulesProfile); } private AbstractObjectAssert<?, QProfileDto> assertQualityProfileFromDb(QProfileDto profile) { return assertThat(db.getDbClient().qualityProfileDao().selectByUuid(dbSession, profile.getKee())); } private void verifyNoCallsActiveRuleIndexerDelete() { verify(activeRuleIndexer, never()).commitDeletionOfProfiles(any(DbSession.class), anyCollection()); } private void verifyCallActiveRuleIndexerDelete(String... expectedRuleProfileUuids) { ArgumentCaptor<Collection<QProfileDto>> collectionCaptor = ArgumentCaptor.forClass(Collection.class); verify(activeRuleIndexer).commitDeletionOfProfiles(any(DbSession.class), collectionCaptor.capture()); assertThat(collectionCaptor.getValue()) .extracting(QProfileDto::getKee) .containsExactlyInAnyOrder(expectedRuleProfileUuids); } private void assertThatRulesProfileExists(RulesProfileDto rulesProfile) { assertThat(db.getDbClient().qualityProfileDao().selectBuiltInRuleProfiles(dbSession)) .extracting(RulesProfileDto::getUuid) .containsExactly(rulesProfile.getUuid()); assertThat(db.countRowsOfTable(dbSession, "active_rules")).isPositive(); assertThat(db.countRowsOfTable(dbSession, "active_rule_parameters")).isPositive(); assertThat(db.countRowsOfTable(dbSession, "qprofile_changes")).isPositive(); } private void assertThatCustomProfileDoesNotExist(QProfileDto profile) { assertThat(db.countSql(dbSession, "select count(*) from org_qprofiles where uuid = '" + profile.getKee() + "'")).isZero(); assertThat(db.countSql(dbSession, "select count(*) from project_qprofiles where profile_key = '" + profile.getKee() + "'")).isZero(); assertThat(db.countSql(dbSession, "select count(*) from default_qprofiles where qprofile_uuid = '" + profile.getKee() + "'")).isZero(); assertThat(db.countSql(dbSession, "select count(*) from rules_profiles where uuid = '" + profile.getRulesProfileUuid() + "'")).isZero(); assertThat(db.countSql(dbSession, "select count(*) from active_rules where profile_uuid = '" + profile.getRulesProfileUuid() + "'")).isZero(); assertThat(db.countSql(dbSession, "select count(*) from qprofile_changes where rules_profile_uuid = '" + profile.getRulesProfileUuid() + "'")).isZero(); // TODO active_rule_parameters } private void assertThatCustomProfileExists(QProfileDto profile) { assertThat(db.countSql(dbSession, "select count(*) from org_qprofiles where uuid = '" + profile.getKee() + "'")).isPositive(); // assertThat(db.countSql(dbSession, "select count(*) from project_qprofiles where profile_key = '" + profile.getKee() + // "'")).isPositive(); // assertThat(db.countSql(dbSession, "select count(*) from default_qprofiles where qprofile_uuid = '" + profile.getKee() + // "'")).isPositive(); assertThat(db.countSql(dbSession, "select count(*) from rules_profiles where uuid = '" + profile.getRulesProfileUuid() + "'")).isOne(); assertThat(db.countSql(dbSession, "select count(*) from active_rules where profile_uuid = '" + profile.getRulesProfileUuid() + "'")).isPositive(); assertThat(db.countSql(dbSession, "select count(*) from qprofile_changes where rules_profile_uuid = '" + profile.getRulesProfileUuid() + "'")).isPositive(); // TODO active_rule_parameters } private static void assertEqual(QProfileDto p1, QProfileDto p2) { assertThat(p2.getName()).isEqualTo(p1.getName()); assertThat(p2.getKee()).startsWith(p1.getKee()); assertThat(p2.getLanguage()).isEqualTo(p1.getLanguage()); assertThat(p2.getRulesProfileUuid()).isEqualTo(p1.getRulesProfileUuid()); assertThat(p2.getParentKee()).isEqualTo(p1.getParentKee()); } private void expectBadRequestException(ThrowingCallable callback, String message) { assertThatThrownBy(callback) .isInstanceOf(BadRequestException.class) .hasMessage(message); } }
14,873
42.238372
160
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileResetImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleKey; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.QualityProfileTesting; import org.sonar.db.rule.RuleDto; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.StringTypeValidation; import org.sonar.server.util.TypeValidations; import static java.util.Arrays.asList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.internal.verification.VerificationModeFactory.times; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED; public class QProfileResetImplIT { private static final String LANGUAGE = "xoo"; @Rule public DbTester db = DbTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private System2 system2 = new AlwaysIncreasingSystem2(); private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class); private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); private TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation())); private RuleActivator ruleActivator = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession); private QProfileTree qProfileTree = new QProfileTreeImpl(db.getDbClient(), ruleActivator, system2, activeRuleIndexer, mock(QualityProfileChangeEventService.class)); private QProfileRules qProfileRules = new QProfileRulesImpl(db.getDbClient(), ruleActivator, null, activeRuleIndexer, qualityProfileChangeEventService); private QProfileResetImpl underTest = new QProfileResetImpl(db.getDbClient(), ruleActivator, activeRuleIndexer, mock(QualityProfileChangeEventService.class)); @Test public void reset() { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE)); RuleDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); qProfileRules.activateAndCommit(db.getSession(), profile, singleton(RuleActivation.create(existingRule.getUuid()))); RuleDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); BulkChangeResult result = underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(newRule.getUuid()))); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)) .extracting(OrgActiveRuleDto::getRuleKey) .containsExactlyInAnyOrder(newRule.getKey()); // Only activated rules are returned in the result assertThat(result.getChanges()) .extracting(ActiveRuleChange::getKey, ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(ActiveRuleKey.of(profile, newRule.getKey()), ACTIVATED)); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void inherited_rules_are_not_disabled() { QProfileDto parentProfile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE)); QProfileDto childProfile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE)); qProfileTree.setParentAndCommit(db.getSession(), childProfile, parentProfile); RuleDto existingRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); qProfileRules.activateAndCommit(db.getSession(), parentProfile, singleton(RuleActivation.create(existingRule.getUuid()))); qProfileRules.activateAndCommit(db.getSession(), childProfile, singleton(RuleActivation.create(existingRule.getUuid()))); RuleDto newRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); underTest.reset(db.getSession(), childProfile, singletonList(RuleActivation.create(newRule.getUuid()))); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), childProfile)) .extracting(OrgActiveRuleDto::getRuleKey) .containsExactlyInAnyOrder(newRule.getKey(), existingRule.getKey()); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(childProfile.getLanguage())); } @Test public void fail_when_profile_is_built_in() { QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(LANGUAGE).setIsBuiltIn(true)); RuleDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); assertThatThrownBy(() -> { underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage(String.format("Operation forbidden for built-in Quality Profile '%s'", profile.getKee())); verifyNoInteractions(qualityProfileChangeEventService); } @Test public void fail_when_profile_is_not_persisted() { QProfileDto profile = QualityProfileTesting.newQualityProfileDto().setRulesProfileUuid(null).setLanguage(LANGUAGE); RuleDto defaultRule = db.rules().insert(r -> r.setLanguage(LANGUAGE)); assertThatThrownBy(() -> { underTest.reset(db.getSession(), profile, singletonList(RuleActivation.create(defaultRule.getUuid()))); }) .isInstanceOf(NullPointerException.class) .hasMessage("Quality profile must be persisted"); verifyNoInteractions(qualityProfileChangeEventService); } }
7,070
50.992647
166
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRuleImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.stream.IntStream; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.PropertyType; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import org.sonar.server.es.EsTester; import org.sonar.server.es.SearchOptions; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.index.RuleQuery; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.StringTypeValidation; import org.sonar.server.util.TypeValidations; import static com.google.common.collect.ImmutableMap.of; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; import static org.sonar.db.rule.RuleTesting.newCustomRule; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; public class QProfileRuleImplIT { private System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); @Rule public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private RuleIndex ruleIndex = new RuleIndex(es.client(), system2); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); private TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation())); private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); private RuleActivator ruleActivator = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession); private QProfileRules underTest = new QProfileRulesImpl(db.getDbClient(), ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService); @Test public void system_activates_rule_without_parameters() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, BLOCKER, null, emptyMap()); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void user_activates_rule_without_parameters() { userSession.logIn(); RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, null); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, BLOCKER, null, emptyMap()); assertThatProfileIsUpdatedByUser(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void activate_rule_with_default_severity_and_parameters() { RuleDto rule = createRule(); RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10")); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, of("min", "10")); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void activate_rule_with_parameters() { RuleDto rule = createRule(); RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10")); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of(ruleParam.getName(), "15")); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, of("min", "15")); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void activate_rule_with_default_severity() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } /** * SONAR-5841 */ @Test public void activate_rule_with_empty_parameter_having_no_default_value() { RuleDto rule = createRule(); RuleParamDto ruleParam = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue("10")); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of("min", "")); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, of("min", "10")); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } /** * // * SONAR-5840 * // */ @Test public void activate_rule_with_negative_integer_value_on_parameter_having_no_default_value() { RuleDto rule = createRule(); RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null)); RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of(paramWithoutDefault.getName(), "-10")); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, of(paramWithoutDefault.getName(), "-10", paramWithDefault.getName(), paramWithDefault.getDefaultValue())); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void activation_ignores_unsupported_parameters() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of("xxx", "yyy")); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, of(param.getName(), param.getDefaultValue())); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void update_an_already_activated_rule() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation RuleActivation activation = RuleActivation.create(rule.getUuid(), MAJOR, null); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // update RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "20")); changes = activate(profile, updateActivation); assertThatRuleIsUpdated(profile, rule, CRITICAL, null, of(param.getName(), "20")); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void update_activation_with_parameter_without_default_value() { RuleDto rule = createRule(); RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null)); RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation -> param "max" has a default value RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); // update param "min", which has no default value RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(paramWithoutDefault.getName(), "3")); changes = activate(profile, updateActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); assertThatRuleIsUpdated(profile, rule, MAJOR, null, of(paramWithDefault.getName(), "10", paramWithoutDefault.getName(), "3")); assertThatProfileIsUpdatedBySystem(profile); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void reset_parameter_to_default_value() { RuleDto rule = createRule(); RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation -> param "max" has a default value RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of(paramWithDefault.getName(), "20")); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // reset to default_value RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), null, of(paramWithDefault.getName(), "")); changes = activate(profile, updateActivation); assertThatRuleIsUpdated(profile, rule, rule.getSeverityString(), null, of(paramWithDefault.getName(), "10")); assertThat(changes).hasSize(1); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void update_activation_removes_parameter_without_default_value() { RuleDto rule = createRule(); RuleParamDto paramWithoutDefault = db.rules().insertRuleParam(rule, p -> p.setName("min").setDefaultValue(null)); RuleParamDto paramWithDefault = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation -> param "max" has a default value RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of(paramWithoutDefault.getName(), "20")); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // remove parameter RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), null, of(paramWithoutDefault.getName(), "")); changes = activate(profile, updateActivation); assertThatRuleIsUpdated(profile, rule, rule.getSeverityString(), null, of(paramWithDefault.getName(), paramWithDefault.getDefaultValue())); assertThat(changes).hasSize(1); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void update_activation_with_new_parameter() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation -> param "max" has a default value RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); db.getDbClient().activeRuleDao().deleteParametersByRuleProfileUuids(db.getSession(), asList(profile.getRulesProfileUuid())); assertThatRuleIsActivated(profile, rule, changes, rule.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // contrary to activerule, the param is supposed to be inserted but not updated RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), null, of(param.getName(), "")); changes = activate(profile, updateActivation); assertThatRuleIsUpdated(profile, rule, rule.getSeverityString(), null, of(param.getName(), param.getDefaultValue())); assertThat(changes).hasSize(1); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void ignore_activation_without_changes() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); // initial activation RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // update with exactly the same severity and params activation = RuleActivation.create(rule.getUuid()); changes = activate(profile, activation); assertThat(changes).isEmpty(); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void do_not_change_severity_and_params_if_unset_and_already_activated() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10")); QProfileDto profile = createProfile(rule); // initial activation -> param "max" has a default value RuleActivation activation = RuleActivation.create(rule.getUuid(), BLOCKER, of(param.getName(), "20")); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // update without any severity or params => keep RuleActivation update = RuleActivation.create(rule.getUuid()); changes = activate(profile, update); assertThat(changes).isEmpty(); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void fail_to_activate_rule_if_profile_is_on_different_languages() { RuleDto rule = createJavaRule(); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage("js")); RuleActivation activation = RuleActivation.create(rule.getUuid()); expectFailure("java rule " + rule.getKey() + " cannot be activated on js profile " + profile.getKee(), () -> activate(profile, activation)); verifyNoInteractions(qualityProfileChangeEventService); } @Test public void fail_to_activate_rule_if_rule_has_REMOVED_status() { RuleDto rule = db.rules().insert(r -> r.setStatus(RuleStatus.REMOVED)); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); expectFailure("Rule was removed: " + rule.getKey(), () -> activate(profile, activation)); verifyNoInteractions(qualityProfileChangeEventService); } @Test public void fail_to_activate_if_template() { RuleDto rule = db.rules().insert(r -> r.setIsTemplate(true)); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); expectFailure("Rule template can't be activated on a Quality profile: " + rule.getKey(), () -> activate(profile, activation)); verifyNoInteractions(qualityProfileChangeEventService); } @Test public void fail_to_activate_if_invalid_parameter() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule, p -> p.setName("max").setDefaultValue("10").setType(PropertyType.INTEGER.name())); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid(), null, of(param.getName(), "foo")); expectFailure("Value 'foo' must be an integer.", () -> activate(profile, activation)); verifyNoInteractions(qualityProfileChangeEventService); } @Test public void ignore_parameters_when_activating_custom_rule() { RuleDto templateRule = db.rules().insert(r -> r.setIsTemplate(true)); RuleParamDto templateParam = db.rules().insertRuleParam(templateRule, p -> p.setName("format")); RuleDto customRule = db.rules().insert(newCustomRule(templateRule)); RuleParamDto customParam = db.rules().insertRuleParam(customRule, p -> p.setName("format").setDefaultValue("txt")); QProfileDto profile = createProfile(customRule); // initial activation RuleActivation activation = RuleActivation.create(customRule.getUuid(), MAJOR, emptyMap()); List<ActiveRuleChange> changes = activate(profile, activation); assertThatRuleIsActivated(profile, customRule, null, MAJOR, null, of("format", "txt")); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); // update -> parameter is not changed RuleActivation updateActivation = RuleActivation.create(customRule.getUuid(), BLOCKER, of("format", "xml")); changes = activate(profile, updateActivation); assertThatRuleIsActivated(profile, customRule, null, BLOCKER, null, of("format", "txt")); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void user_deactivates_a_rule() { userSession.logIn(); RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); changes = deactivate(profile, rule); verifyNoActiveRules(); assertThatProfileIsUpdatedByUser(profile); assertThat(changes).hasSize(1); assertThat(changes.get(0).getType()).isEqualTo(ActiveRuleChange.Type.DEACTIVATED); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void system_deactivates_a_rule() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); changes = deactivate(profile, rule); verifyNoActiveRules(); assertThatProfileIsUpdatedBySystem(profile); assertThatChangeIsDeactivation(changes, rule); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } private void assertThatChangeIsDeactivation(List<ActiveRuleChange> changes, RuleDto rule) { assertThat(changes).hasSize(1); ActiveRuleChange change = changes.get(0); assertThat(change.getType()).isEqualTo(ActiveRuleChange.Type.DEACTIVATED); assertThat(change.getKey().getRuleKey()).isEqualTo(rule.getKey()); } @Test public void ignore_deactivation_if_rule_is_not_activated() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); List<ActiveRuleChange> changes = deactivate(profile, rule); verifyNoActiveRules(); assertThat(changes).isEmpty(); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(profile.getLanguage())); } @Test public void deactivate_rule_that_has_REMOVED_status() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(profile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); rule.setStatus(RuleStatus.REMOVED); db.getDbClient().ruleDao().update(db.getSession(), rule); changes = deactivate(profile, rule); verifyNoActiveRules(); assertThatChangeIsDeactivation(changes, rule); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(profile.getLanguage())); } @Test public void activation_on_child_profile_is_propagated_to_descendants() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); List<ActiveRuleChange> changes = activate(childProfile, RuleActivation.create(rule.getUuid())); assertThatProfileHasNoActiveRules(parentProfile); assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(grandChildProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap()); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(childProfile.getLanguage())); } @Test public void update_on_child_profile_is_propagated_to_descendants() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); System.out.println("ACTIVATE ON " + childProfile.getName()); RuleActivation initialActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(childProfile, initialActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); System.out.println("---------------"); System.out.println("ACTIVATE ON " + childProfile.getName()); RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "bar")); changes = activate(childProfile, updateActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); assertThatProfileHasNoActiveRules(parentProfile); assertThatRuleIsUpdated(childProfile, rule, CRITICAL, null, of(param.getName(), "bar")); assertThatRuleIsUpdated(grandChildProfile, rule, CRITICAL, INHERITED, of(param.getName(), "bar")); assertThat(changes).hasSize(2); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); } @Test public void override_activation_of_inherited_profile() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); RuleActivation initialActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(childProfile, initialActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); RuleActivation overrideActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "bar")); changes = activate(grandChildProfile, overrideActivation); assertThatProfileHasNoActiveRules(parentProfile); assertThatRuleIsUpdated(childProfile, rule, MAJOR, null, of(param.getName(), "foo")); assertThatRuleIsUpdated(grandChildProfile, rule, CRITICAL, ActiveRuleInheritance.OVERRIDES, of(param.getName(), "bar")); assertThat(changes).hasSize(1); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); } @Test public void updated_activation_on_parent_is_not_propagated_to_overridden_profiles() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); RuleActivation initialActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(childProfile, initialActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); RuleActivation overrideActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "bar")); changes = activate(grandChildProfile, overrideActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(grandChildProfile.getLanguage())); // update child --> do not touch grandChild RuleActivation updateActivation = RuleActivation.create(rule.getUuid(), BLOCKER, of(param.getName(), "baz")); changes = activate(childProfile, updateActivation); assertThatProfileHasNoActiveRules(parentProfile); assertThatRuleIsUpdated(childProfile, rule, BLOCKER, null, of(param.getName(), "baz")); assertThatRuleIsUpdated(grandChildProfile, rule, CRITICAL, ActiveRuleInheritance.OVERRIDES, of(param.getName(), "bar")); assertThat(changes).hasSize(1); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); } @Test public void reset_on_parent_is_not_propagated_to_overridden_profiles() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); RuleActivation initialActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(parentProfile, initialActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); RuleActivation overrideActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "bar")); changes = activate(grandChildProfile, overrideActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(grandChildProfile.getLanguage())); // reset parent --> touch child but not grandChild RuleActivation updateActivation = RuleActivation.createReset(rule.getUuid()); changes = activate(parentProfile, updateActivation); Map<String, String> test = new HashMap<>(); test.put(param.getName(), param.getDefaultValue()); assertThatRuleIsUpdated(parentProfile, rule, rule.getSeverityString(), null, test); assertThatRuleIsUpdated(childProfile, rule, rule.getSeverityString(), INHERITED, of(param.getName(), param.getDefaultValue())); assertThatRuleIsUpdated(grandChildProfile, rule, CRITICAL, ActiveRuleInheritance.OVERRIDES, of(param.getName(), "bar")); assertThat(changes).hasSize(2); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); } @Test public void active_on_parent_a_rule_already_activated_on_child() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation childActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(childProfile, childActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); RuleActivation parentActivation = RuleActivation.create(rule.getUuid(), CRITICAL, of(param.getName(), "bar")); changes = activate(parentProfile, parentActivation); assertThatRuleIsUpdated(parentProfile, rule, CRITICAL, null, of(param.getName(), "bar")); assertThatRuleIsUpdated(childProfile, rule, MAJOR, ActiveRuleInheritance.OVERRIDES, of(param.getName(), "foo")); assertThat(changes).hasSize(2); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); } @Test public void do_not_mark_as_overridden_if_same_values_than_parent() { RuleDto rule = createRule(); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation parentActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); List<ActiveRuleChange> changes = activate(parentProfile, parentActivation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); RuleActivation overrideActivation = RuleActivation.create(rule.getUuid(), MAJOR, of(param.getName(), "foo")); changes = activate(childProfile, overrideActivation); assertThatRuleIsUpdated(childProfile, rule, MAJOR, INHERITED, of(param.getName(), "foo")); assertThat(changes).isEmpty(); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); } @Test public void propagate_deactivation_on_children() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(parentProfile, activation); assertThatRuleIsActivated(parentProfile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap()); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); changes = deactivate(parentProfile, rule); assertThatProfileHasNoActiveRules(parentProfile); assertThatProfileHasNoActiveRules(childProfile); assertThat(changes).hasSize(2); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); } @Test public void propagate_deactivation_on_children_even_when_overridden() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(parentProfile, activation); assertThatRuleIsActivated(parentProfile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap()); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); activation = RuleActivation.create(rule.getUuid(), CRITICAL, null); changes = activate(childProfile, activation); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(childProfile.getLanguage())); changes = deactivate(parentProfile, rule); assertThatProfileHasNoActiveRules(parentProfile); assertThatProfileHasNoActiveRules(childProfile); assertThat(changes).hasSize(2); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), eq(changes), eq(parentProfile.getLanguage())); } @Test public void cannot_deactivate_rule_inherited() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation activation = RuleActivation.create(rule.getUuid()); List<ActiveRuleChange> changes = activate(parentProfile, activation); assertThatRuleIsActivated(parentProfile, rule, changes, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, rule.getSeverityString(), INHERITED, emptyMap()); assertThatThrownBy(() -> deactivate(childProfile, rule)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Cannot deactivate inherited rule"); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(parentProfile.getLanguage())); } @Test public void reset_child_profile_do_not_change_parent() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); RuleActivation activation = RuleActivation.create(rule.getUuid(), CRITICAL, null); List<ActiveRuleChange> changes = activate(parentProfile, activation); assertThatRuleIsActivated(parentProfile, rule, changes, CRITICAL, null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, CRITICAL, INHERITED, emptyMap()); assertThat(changes).hasSize(2); RuleActivation childActivation = RuleActivation.create(rule.getUuid(), BLOCKER, null); changes = activate(childProfile, childActivation); assertThatRuleIsUpdated(childProfile, rule, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThat(changes).hasSize(1); RuleActivation resetActivation = RuleActivation.createReset(rule.getUuid()); changes = activate(childProfile, resetActivation); assertThatRuleIsUpdated(childProfile, rule, CRITICAL, INHERITED, emptyMap()); assertThatRuleIsUpdated(parentProfile, rule, CRITICAL, null, emptyMap()); assertThat(changes).hasSize(1); } @Test public void reset_parent_is_not_propagated_when_child_overrides() { RuleDto rule = createRule(); QProfileDto baseProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(baseProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); RuleActivation activation = RuleActivation.create(rule.getUuid(), CRITICAL, null); List<ActiveRuleChange> changes = activate(baseProfile, activation); assertThatRuleIsActivated(baseProfile, rule, changes, CRITICAL, null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, changes, CRITICAL, INHERITED, emptyMap()); assertThatRuleIsActivated(grandChildProfile, rule, changes, CRITICAL, INHERITED, emptyMap()); assertThat(changes).hasSize(3); RuleActivation childActivation = RuleActivation.create(rule.getUuid(), BLOCKER, null); changes = activate(childProfile, childActivation); assertThatRuleIsUpdated(childProfile, rule, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThatRuleIsUpdated(grandChildProfile, rule, BLOCKER, INHERITED, emptyMap()); assertThat(changes).hasSize(2); // Reset on parent do not change child nor grandchild RuleActivation resetActivation = RuleActivation.createReset(rule.getUuid()); changes = activate(baseProfile, resetActivation); assertThatRuleIsUpdated(baseProfile, rule, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsUpdated(childProfile, rule, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThatRuleIsUpdated(grandChildProfile, rule, BLOCKER, INHERITED, emptyMap()); assertThat(changes).hasSize(1); // Reset on child change grandchild resetActivation = RuleActivation.createReset(rule.getUuid()); changes = activate(childProfile, resetActivation); assertThatRuleIsUpdated(baseProfile, rule, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsUpdated(childProfile, rule, rule.getSeverityString(), INHERITED, emptyMap()); assertThatRuleIsUpdated(grandChildProfile, rule, rule.getSeverityString(), INHERITED, emptyMap()); assertThat(changes).hasSize(2); } @Test public void ignore_reset_if_not_activated() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); createChildProfile(parentProfile); RuleActivation resetActivation = RuleActivation.createReset(rule.getUuid()); List<ActiveRuleChange> changes = activate(parentProfile, resetActivation); verifyNoActiveRules(); assertThat(changes).isEmpty(); } @Test public void bulk_activation() { int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100); String language = randomAlphanumeric(10); String repositoryKey = randomAlphanumeric(10); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language)); List<RuleDto> rules = new ArrayList<>(); IntStream.rangeClosed(1, bulkSize).forEach( i -> rules.add(db.rules().insertRule(r -> r.setLanguage(language).setRepositoryKey(repositoryKey)))); verifyNoActiveRules(); ruleIndexer.indexAll(); RuleQuery ruleQuery = new RuleQuery() .setRepositories(singletonList(repositoryKey)); BulkChangeResult bulkChangeResult = underTest.bulkActivateAndCommit(db.getSession(), profile, ruleQuery, MINOR); assertThat(bulkChangeResult.countFailed()).isZero(); assertThat(bulkChangeResult.countSucceeded()).isEqualTo(bulkSize); assertThat(bulkChangeResult.getChanges()).hasSize(bulkSize); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)).hasSize(bulkSize); rules.forEach(r -> assertThatRuleIsActivated(profile, r, null, MINOR, null, emptyMap())); } @Test public void bulk_deactivation() { int bulkSize = SearchOptions.MAX_PAGE_SIZE + 10 + new Random().nextInt(100); String language = randomAlphanumeric(10); String repositoryKey = randomAlphanumeric(10); QProfileDto profile = db.qualityProfiles().insert(p -> p.setLanguage(language)); List<RuleDto> rules = new ArrayList<>(); IntStream.rangeClosed(1, bulkSize).forEach( i -> rules.add(db.rules().insertRule(r -> r.setLanguage(language).setRepositoryKey(repositoryKey)))); verifyNoActiveRules(); ruleIndexer.indexAll(); RuleQuery ruleQuery = new RuleQuery() .setRepositories(singletonList(repositoryKey)); BulkChangeResult bulkChangeResult = underTest.bulkActivateAndCommit(db.getSession(), profile, ruleQuery, MINOR); assertThat(bulkChangeResult.countFailed()).isZero(); assertThat(bulkChangeResult.countSucceeded()).isEqualTo(bulkSize); assertThat(bulkChangeResult.getChanges()).hasSize(bulkSize); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)).hasSize(bulkSize); // Now deactivate all rules bulkChangeResult = underTest.bulkDeactivateAndCommit(db.getSession(), profile, ruleQuery); assertThat(bulkChangeResult.countFailed()).isZero(); assertThat(bulkChangeResult.countSucceeded()).isEqualTo(bulkSize); assertThat(bulkChangeResult.getChanges()).hasSize(bulkSize); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile)).isEmpty(); rules.forEach(r -> assertThatRuleIsNotPresent(profile, r)); } @Test public void bulk_deactivation_ignores_errors() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); List<ActiveRuleChange> changes = activate(parentProfile, RuleActivation.create(rule.getUuid())); assertThatRuleIsActivated(parentProfile, rule, null, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, null, rule.getSeverityString(), INHERITED, emptyMap()); ruleIndexer.indexAll(); RuleQuery ruleQuery = new RuleQuery() .setQProfile(childProfile); BulkChangeResult bulkChangeResult = underTest.bulkDeactivateAndCommit(db.getSession(), childProfile, ruleQuery); assertThat(bulkChangeResult.countFailed()).isOne(); assertThat(bulkChangeResult.countSucceeded()).isZero(); assertThat(bulkChangeResult.getChanges()).isEmpty(); assertThatRuleIsActivated(parentProfile, rule, null, rule.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule, null, rule.getSeverityString(), INHERITED, emptyMap()); } @Test public void bulk_change_severity() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); QProfileDto parentProfile = createProfile(rule1); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandchildProfile = createChildProfile(childProfile); activate(parentProfile, RuleActivation.create(rule1.getUuid())); activate(parentProfile, RuleActivation.create(rule2.getUuid())); ruleIndexer.indexAll(); RuleQuery query = new RuleQuery() .setRuleKey(rule1.getRuleKey()) .setQProfile(parentProfile); BulkChangeResult result = underTest.bulkActivateAndCommit(db.getSession(), parentProfile, query, "BLOCKER"); assertThat(result.getChanges()).hasSize(3); assertThat(result.countSucceeded()).isOne(); assertThat(result.countFailed()).isZero(); // Rule1 must be activated with BLOCKER on all profiles assertThatRuleIsActivated(parentProfile, rule1, null, BLOCKER, null, emptyMap()); assertThatRuleIsActivated(childProfile, rule1, null, BLOCKER, INHERITED, emptyMap()); assertThatRuleIsActivated(grandchildProfile, rule1, null, BLOCKER, INHERITED, emptyMap()); // Rule2 did not changed assertThatRuleIsActivated(parentProfile, rule2, null, rule2.getSeverityString(), null, emptyMap()); assertThatRuleIsActivated(childProfile, rule2, null, rule2.getSeverityString(), INHERITED, emptyMap()); assertThatRuleIsActivated(grandchildProfile, rule2, null, rule2.getSeverityString(), INHERITED, emptyMap()); } @Test public void delete_rule_from_all_profiles() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandChildProfile = createChildProfile(childProfile); RuleActivation activation = RuleActivation.create(rule.getUuid(), CRITICAL, null); activate(parentProfile, activation); RuleActivation overrideActivation = RuleActivation.create(rule.getUuid(), BLOCKER, null); activate(grandChildProfile, overrideActivation); // Reset on parent do not change child nor grandchild List<ActiveRuleChange> changes = underTest.deleteRule(db.getSession(), rule); assertThatRuleIsNotPresent(parentProfile, rule); assertThatRuleIsNotPresent(childProfile, rule); assertThatRuleIsNotPresent(grandChildProfile, rule); assertThat(changes) .extracting(ActiveRuleChange::getType) .containsOnly(ActiveRuleChange.Type.DEACTIVATED) .hasSize(3); } @Test public void activation_fails_when_profile_is_built_in() { RuleDto rule = createRule(); QProfileDto builtInProfile = db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage()).setIsBuiltIn(true)); assertThatThrownBy(() -> { underTest.activateAndCommit(db.getSession(), builtInProfile, singleton(RuleActivation.create(rule.getUuid()))); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("The built-in profile " + builtInProfile.getName() + " is read-only and can't be updated"); } private void assertThatProfileHasNoActiveRules(QProfileDto profile) { List<OrgActiveRuleDto> activeRules = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile); assertThat(activeRules).isEmpty(); } private List<ActiveRuleChange> deactivate(QProfileDto profile, RuleDto rule) { return underTest.deactivateAndCommit(db.getSession(), profile, singleton(rule.getUuid())); } private List<ActiveRuleChange> activate(QProfileDto profile, RuleActivation activation) { return underTest.activateAndCommit(db.getSession(), profile, singleton(activation)); } private QProfileDto createProfile(RuleDto rule) { return db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage())); } private QProfileDto createChildProfile(QProfileDto parent) { return db.qualityProfiles().insert(p -> p .setLanguage(parent.getLanguage()) .setParentKee(parent.getKee()) .setName("Child of " + parent.getName())); } private void assertThatProfileIsUpdatedByUser(QProfileDto profile) { QProfileDto loaded = db.getDbClient().qualityProfileDao().selectByUuid(db.getSession(), profile.getKee()); assertThat(loaded.getUserUpdatedAt()).isNotNull(); assertThat(loaded.getRulesUpdatedAt()).isNotEmpty(); } private void assertThatProfileIsUpdatedBySystem(QProfileDto profile) { QProfileDto loaded = db.getDbClient().qualityProfileDao().selectByUuid(db.getSession(), profile.getKee()); assertThat(loaded.getUserUpdatedAt()).isNull(); assertThat(loaded.getRulesUpdatedAt()).isNotEmpty(); } private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes, String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst() .orElseThrow(IllegalStateException::new); assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity); assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null); List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid()); assertThat(params).hasSize(expectedParams.size()); if (changes != null) { ActiveRuleChange change = changes.stream() .filter(c -> c.getActiveRule().getUuid().equals(activeRule.getUuid())) .findFirst().orElseThrow(IllegalStateException::new); assertThat(change.getInheritance()).isEqualTo(expectedInheritance); assertThat(change.getSeverity()).isEqualTo(expectedSeverity); assertThat(change.getType()).isEqualTo(ActiveRuleChange.Type.ACTIVATED); } } private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDto rule) { Optional<OrgActiveRuleDto> activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst(); assertThat(activeRule).isEmpty(); } private void assertThatRuleIsUpdated(QProfileDto profile, RuleDto rule, String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst() .orElseThrow(IllegalStateException::new); assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity); assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null); List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid()); assertThat(params).hasSize(expectedParams.size()); } private void expectFailure(String expectedMessage, Runnable runnable) { try { runnable.run(); fail(); } catch (BadRequestException e) { assertThat(e.getMessage()).isEqualTo(expectedMessage); } verifyNoActiveRules(); } private void verifyNoActiveRules() { assertThat(db.countRowsOfTable(db.getSession(), "active_rules")).isZero(); } private RuleDto createRule() { return db.rules().insert(r -> r.setSeverity(Severity.MAJOR)); } private RuleDto createJavaRule() { return db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("java")); } }
51,625
48.976767
155
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileRulesImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import com.google.common.collect.ImmutableMap; import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.QProfileChangeDto; import org.sonar.db.qualityprofile.QProfileChangeQuery; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.user.UserDto; import org.sonar.server.es.EsTester; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.TypeValidations; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class QProfileRulesImplIT { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @Rule public DbTester db = DbTester.create(); @Rule public EsTester es = EsTester.create(); private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, db.getDbClient(), new TypeValidations(singletonList(new IntegerTypeValidation())), userSession); private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); private QProfileRules qProfileRules = new QProfileRulesImpl(db.getDbClient(), ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService); @Test public void activate_one_rule() { QProfileDto qProfile = db.qualityProfiles().insert(); RuleDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage())); RuleActivation ruleActivation = RuleActivation.create(rule.getUuid(), Severity.CRITICAL, Collections.emptyMap()); qProfileRules.activateAndCommit(db.getSession(), qProfile, singleton(ruleActivation)); assertThat(db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), qProfile)) .extracting(ActiveRuleDto::getRuleKey, ActiveRuleDto::getSeverityString) .containsExactlyInAnyOrder(tuple(rule.getKey(), Severity.CRITICAL)); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(qProfile.getLanguage())); } @Test public void active_rule_change() { UserDto user = db.users().insertUser(); userSession.logIn(user); QProfileDto qProfile = db.qualityProfiles().insert(); RuleDto rule = db.rules().insert(r -> r.setLanguage(qProfile.getLanguage())); RuleActivation ruleActivation = RuleActivation.create(rule.getUuid(), Severity.CRITICAL, Collections.emptyMap()); qProfileRules.activateAndCommit(db.getSession(), qProfile, singleton(ruleActivation)); assertThat(db.getDbClient().qProfileChangeDao().selectByQuery(db.getSession(), new QProfileChangeQuery(qProfile.getKee()))) .extracting(QProfileChangeDto::getUserUuid, QProfileChangeDto::getDataAsMap) .containsExactlyInAnyOrder(tuple(user.getUuid(), ImmutableMap.of("ruleUuid", rule.getUuid(), "severity", Severity.CRITICAL))); verify(qualityProfileChangeEventService).distributeRuleChangeEvent(any(), any(), eq(qProfile.getLanguage())); } }
4,760
46.61
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/QProfileTreeImplIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.qualityprofile.OrgActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.es.EsTester; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.IntegerTypeValidation; import org.sonar.server.util.StringTypeValidation; import org.sonar.server.util.TypeValidations; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.server.qualityprofile.ActiveRuleInheritance.INHERITED; public class QProfileTreeImplIT { private System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); @Rule public EsTester es = EsTester.create(); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); private TypeValidations typeValidations = new TypeValidations(asList(new StringTypeValidation(), new IntegerTypeValidation())); private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); private RuleActivator ruleActivator = new RuleActivator(system2, db.getDbClient(), typeValidations, userSession); private QProfileRules qProfileRules = new QProfileRulesImpl(db.getDbClient(), ruleActivator, null, activeRuleIndexer, qualityProfileChangeEventService); private QProfileTree underTest = new QProfileTreeImpl(db.getDbClient(), ruleActivator, System2.INSTANCE, activeRuleIndexer, mock(QualityProfileChangeEventService.class)); @Test public void set_itself_as_parent_fails() { RuleDto rule = createRule(); QProfileDto profile = createProfile(rule); assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), profile, profile)) .isInstanceOf(BadRequestException.class) .hasMessageContaining(" can not be selected as parent of "); } @Test public void set_child_as_parent_fails() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), parentProfile, childProfile)) .isInstanceOf(BadRequestException.class) .hasMessageContaining(" can not be selected as parent of "); } @Test public void set_grandchild_as_parent_fails() { RuleDto rule = createRule(); QProfileDto parentProfile = createProfile(rule); QProfileDto childProfile = createChildProfile(parentProfile); QProfileDto grandchildProfile = createChildProfile(childProfile); assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), parentProfile, grandchildProfile)) .isInstanceOf(BadRequestException.class) .hasMessageContaining(" can not be selected as parent of "); } @Test public void cannot_set_parent_if_language_is_different() { RuleDto rule1 = db.rules().insert(r -> r.setLanguage("foo")); RuleDto rule2 = db.rules().insert(r -> r.setLanguage("bar")); QProfileDto parentProfile = createProfile(rule1); List<ActiveRuleChange> changes = activate(parentProfile, RuleActivation.create(rule1.getUuid())); assertThat(changes).hasSize(1); QProfileDto childProfile = createProfile(rule2); changes = activate(childProfile, RuleActivation.create(rule2.getUuid())); assertThat(changes).hasSize(1); assertThatThrownBy(() -> underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile)) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Cannot set the profile"); } @Test public void set_then_unset_parent() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); QProfileDto profile1 = createProfile(rule1); List<ActiveRuleChange> changes = activate(profile1, RuleActivation.create(rule1.getUuid())); assertThat(changes).hasSize(1); QProfileDto profile2 = createProfile(rule2); changes = activate(profile2, RuleActivation.create(rule2.getUuid())); assertThat(changes).hasSize(1); changes = underTest.setParentAndCommit(db.getSession(), profile2, profile1); assertThat(changes).hasSize(1); assertThatRuleIsActivated(profile2, rule1, changes, rule1.getSeverityString(), INHERITED, emptyMap()); assertThatRuleIsActivated(profile2, rule2, null, rule2.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(profile2.getLanguage())); changes = underTest.removeParentAndCommit(db.getSession(), profile2); assertThat(changes).hasSize(1); assertThatRuleIsActivated(profile2, rule2, null, rule2.getSeverityString(), null, emptyMap()); assertThatRuleIsNotPresent(profile2, rule1); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(profile2.getLanguage())); } @Test public void set_then_unset_parent_keep_overridden_rules() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); QProfileDto profile1 = createProfile(rule1); List<ActiveRuleChange> changes = activate(profile1, RuleActivation.create(rule1.getUuid())); assertThat(changes).hasSize(1); QProfileDto profile2 = createProfile(rule2); changes = activate(profile2, RuleActivation.create(rule2.getUuid())); assertThat(changes).hasSize(1); changes = underTest.setParentAndCommit(db.getSession(), profile2, profile1); assertThat(changes).hasSize(1); assertThatRuleIsActivated(profile2, rule1, changes, rule1.getSeverityString(), INHERITED, emptyMap()); assertThatRuleIsActivated(profile2, rule2, null, rule2.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(profile2.getLanguage())); RuleActivation activation = RuleActivation.create(rule1.getUuid(), BLOCKER, null); changes = activate(profile2, activation); assertThat(changes).hasSize(1); assertThatRuleIsUpdated(profile2, rule1, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThatRuleIsActivated(profile2, rule2, null, rule2.getSeverityString(), null, emptyMap()); changes = underTest.removeParentAndCommit(db.getSession(), profile2); assertThat(changes).hasSize(1); // Not testing changes here since severity is not set in changelog assertThatRuleIsActivated(profile2, rule1, null, BLOCKER, null, emptyMap()); assertThatRuleIsActivated(profile2, rule2, null, rule2.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService, times(3)).distributeRuleChangeEvent(anyList(), any(), eq(profile2.getLanguage())); } @Test public void change_parent_keep_overridden_rules() { RuleDto parentRule = createJavaRule(); RuleDto childRule = createJavaRule(); QProfileDto parentProfile1 = createProfile(parentRule); List<ActiveRuleChange> changes = activate(parentProfile1, RuleActivation.create(parentRule.getUuid())); assertThat(changes).hasSize(1); QProfileDto childProfile = createProfile(childRule); changes = activate(childProfile, RuleActivation.create(childRule.getUuid())); assertThat(changes).hasSize(1); changes = underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile1); assertThat(changes).hasSize(1); assertThatRuleIsActivated(childProfile, parentRule, changes, parentRule.getSeverityString(), INHERITED, emptyMap()); assertThatRuleIsActivated(childProfile, childRule, null, childRule.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(childProfile.getLanguage())); RuleActivation activation = RuleActivation.create(parentRule.getUuid(), BLOCKER, null); changes = activate(childProfile, activation); assertThat(changes).hasSize(1); assertThatRuleIsUpdated(childProfile, parentRule, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThatRuleIsActivated(childProfile, childRule, null, childRule.getSeverityString(), null, emptyMap()); QProfileDto parentProfile2 = createProfile(parentRule); changes = activate(parentProfile2, RuleActivation.create(parentRule.getUuid())); assertThat(changes).hasSize(1); changes = underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile2); assertThat(changes).isEmpty(); assertThatRuleIsUpdated(childProfile, parentRule, BLOCKER, ActiveRuleInheritance.OVERRIDES, emptyMap()); assertThatRuleIsActivated(childProfile, childRule, null, childRule.getSeverityString(), null, emptyMap()); verify(qualityProfileChangeEventService, times(4)).distributeRuleChangeEvent(any(), any(), eq(childProfile.getLanguage())); } @Test public void activation_errors_are_ignored_when_setting_a_parent() { RuleDto rule1 = createJavaRule(); RuleDto rule2 = createJavaRule(); QProfileDto parentProfile = createProfile(rule1); activate(parentProfile, RuleActivation.create(rule1.getUuid())); activate(parentProfile, RuleActivation.create(rule2.getUuid())); rule1.setStatus(RuleStatus.REMOVED); db.rules().update(rule1); QProfileDto childProfile = createProfile(rule1); List<ActiveRuleChange> changes = underTest.setParentAndCommit(db.getSession(), childProfile, parentProfile); verify(qualityProfileChangeEventService, times(2)).distributeRuleChangeEvent(any(), any(), eq(childProfile.getLanguage())); assertThatRuleIsNotPresent(childProfile, rule1); assertThatRuleIsActivated(childProfile, rule2, changes, rule2.getSeverityString(), INHERITED, emptyMap()); } private List<ActiveRuleChange> activate(QProfileDto profile, RuleActivation activation) { return qProfileRules.activateAndCommit(db.getSession(), profile, singleton(activation)); } private QProfileDto createProfile(RuleDto rule) { return db.qualityProfiles().insert(p -> p.setLanguage(rule.getLanguage())); } private QProfileDto createChildProfile(QProfileDto parent) { return db.qualityProfiles().insert(p -> p .setLanguage(parent.getLanguage()) .setParentKee(parent.getKee()) .setName("Child of " + parent.getName())); } private void assertThatRuleIsActivated(QProfileDto profile, RuleDto rule, @Nullable List<ActiveRuleChange> changes, String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst() .orElseThrow(IllegalStateException::new); assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity); assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null); List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid()); assertThat(params).hasSize(expectedParams.size()); if (changes != null) { ActiveRuleChange change = changes.stream() .filter(c -> c.getActiveRule().getUuid().equals(activeRule.getUuid())) .findFirst().orElseThrow(IllegalStateException::new); assertThat(change.getInheritance()).isEqualTo(expectedInheritance); assertThat(change.getSeverity()).isEqualTo(expectedSeverity); assertThat(change.getType()).isEqualTo(ActiveRuleChange.Type.ACTIVATED); } } private void assertThatRuleIsNotPresent(QProfileDto profile, RuleDto rule) { Optional<OrgActiveRuleDto> activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst(); assertThat(activeRule).isEmpty(); } private void assertThatRuleIsUpdated(QProfileDto profile, RuleDto rule, String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst() .orElseThrow(IllegalStateException::new); assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity); assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null); List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleUuid(db.getSession(), activeRule.getUuid()); assertThat(params).hasSize(expectedParams.size()); } private RuleDto createRule() { return db.rules().insert(r -> r.setSeverity(Severity.MAJOR)); } private RuleDto createJavaRule() { return db.rules().insert(r -> r.setSeverity(Severity.MAJOR).setLanguage("java")); } }
15,094
47.38141
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.resources.Language; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.RulesProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.language.LanguageTesting; import org.sonar.server.qualityprofile.builtin.BuiltInQProfile; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsert; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileRepositoryRule; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdate; import org.sonar.server.qualityprofile.builtin.BuiltInQualityProfilesUpdateListener; import org.sonar.server.tester.UserSessionRule; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto; import static org.sonar.db.qualityprofile.QualityProfileTesting.newRuleProfileDto; public class RegisterQualityProfilesIT { private static final Language FOO_LANGUAGE = LanguageTesting.newLanguage("foo"); private static final Language BAR_LANGUAGE = LanguageTesting.newLanguage("bar"); private final System2 system2 = new TestSystem2().setNow(1659510722633L); @Rule public DbTester db = DbTester.create(system2); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule public BuiltInQProfileRepositoryRule builtInQProfileRepositoryRule = new BuiltInQProfileRepositoryRule(); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = db.getDbClient(); private final DummyBuiltInQProfileInsert insert = new DummyBuiltInQProfileInsert(); private final DummyBuiltInQProfileUpdate update = new DummyBuiltInQProfileUpdate(); private final RegisterQualityProfiles underTest = new RegisterQualityProfiles(builtInQProfileRepositoryRule, dbClient, insert, update, mock(BuiltInQualityProfilesUpdateListener.class), system2); @Test public void start_fails_if_BuiltInQProfileRepository_has_not_been_initialized() { assertThatThrownBy(underTest::start) .isInstanceOf(IllegalStateException.class) .hasMessage("initialize must be called first"); } @Test public void persist_built_in_profiles_that_are_not_persisted_yet() { BuiltInQProfile builtInQProfile = builtInQProfileRepositoryRule.add(FOO_LANGUAGE, "Sonar way"); builtInQProfileRepositoryRule.initialize(); underTest.start(); assertThat(insert.callLogs).containsExactly(builtInQProfile); assertThat(update.callLogs).isEmpty(); assertThat(logTester.logs(Level.INFO)).contains("Register profile foo/Sonar way"); } @Test public void dont_persist_built_in_profiles_that_are_already_persisted() { String name = "doh"; BuiltInQProfile persistedBuiltIn = builtInQProfileRepositoryRule.add(FOO_LANGUAGE, name, true); BuiltInQProfile nonPersistedBuiltIn = builtInQProfileRepositoryRule.add(BAR_LANGUAGE, name, true); builtInQProfileRepositoryRule.initialize(); insertRulesProfile(persistedBuiltIn); underTest.start(); assertThat(insert.callLogs).containsExactly(nonPersistedBuiltIn); assertThat(update.callLogs).containsExactly(persistedBuiltIn); } @Test public void rename_custom_outdated_profiles_if_same_name_than_built_in_profile() { QProfileDto outdatedProfile = db.qualityProfiles().insert(p -> p.setIsBuiltIn(false) .setLanguage(FOO_LANGUAGE.getKey()).setName("Sonar way")); builtInQProfileRepositoryRule.add(FOO_LANGUAGE, "Sonar way", false); builtInQProfileRepositoryRule.initialize(); underTest.start(); assertThat(selectPersistedName(outdatedProfile)).isEqualTo("Sonar way (outdated copy)"); assertThat(logTester.logs(Level.INFO)).contains("Rename Quality profiles [foo/Sonar way] to [Sonar way (outdated copy)]"); } @Test public void update_built_in_profile_if_it_already_exists() { RulesProfileDto ruleProfile = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Sonar way").setLanguage(FOO_LANGUAGE.getKey())); db.getDbClient().qualityProfileDao().insert(db.getSession(), ruleProfile); db.commit(); BuiltInQProfile builtIn = builtInQProfileRepositoryRule.add(FOO_LANGUAGE, ruleProfile.getName(), false); builtInQProfileRepositoryRule.initialize(); underTest.start(); assertThat(insert.callLogs).isEmpty(); assertThat(update.callLogs).containsExactly(builtIn); assertThat(logTester.logs(Level.INFO)).contains("Update profile foo/Sonar way"); } @Test public void update_default_built_in_quality_profile() { RulesProfileDto ruleProfileWithoutRule = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Sonar way").setLanguage(FOO_LANGUAGE.getKey())); RulesProfileDto ruleProfileWithOneRule = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Sonar way 2").setLanguage(FOO_LANGUAGE.getKey())); QProfileDto qProfileWithoutRule = newQualityProfileDto() .setIsBuiltIn(true) .setLanguage(FOO_LANGUAGE.getKey()) .setName("Sonar way") .setRulesProfileUuid(ruleProfileWithoutRule.getUuid()); QProfileDto qProfileWithOneRule = newQualityProfileDto() .setIsBuiltIn(true) .setName("Sonar way 2") .setLanguage(FOO_LANGUAGE.getKey()) .setRulesProfileUuid(ruleProfileWithOneRule.getUuid()); db.qualityProfiles().insert(qProfileWithoutRule, qProfileWithOneRule); db.qualityProfiles().setAsDefault(qProfileWithoutRule); RuleDto ruleDto = db.rules().insert(); db.qualityProfiles().activateRule(qProfileWithOneRule, ruleDto); db.commit(); builtInQProfileRepositoryRule.add(FOO_LANGUAGE, ruleProfileWithoutRule.getName(), true); builtInQProfileRepositoryRule.add(FOO_LANGUAGE, ruleProfileWithOneRule.getName(), false); builtInQProfileRepositoryRule.initialize(); underTest.start(); assertThat(logTester.logs(Level.INFO)).containsAnyOf( format("Default built-in quality profile for language [foo] has been updated from [%s] to [%s] since previous default does not have active rules.", qProfileWithoutRule.getName(), qProfileWithOneRule.getName())); assertThat(selectUuidOfDefaultProfile(FOO_LANGUAGE.getKey())) .isPresent().get() .isEqualTo(qProfileWithOneRule.getKee()); } @Test public void rename_and_drop_built_in_flag_for_quality_profile() { System.out.println(System.currentTimeMillis()); RulesProfileDto ruleProfileWithoutRule = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Foo way").setLanguage(FOO_LANGUAGE.getKey())); RulesProfileDto ruleProfileLongNameWithoutRule = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("That's a very very very very very very " + "very very very very long name").setLanguage(FOO_LANGUAGE.getKey())); RulesProfileDto ruleProfileWithOneRuleToBeRenamed = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Foo way 2").setLanguage(FOO_LANGUAGE.getKey())); RulesProfileDto ruleProfileWithOneRule = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setName("Foo way 3").setLanguage(FOO_LANGUAGE.getKey())); QProfileDto qProfileWithoutRule = newQualityProfileDto() .setIsBuiltIn(true) .setLanguage(FOO_LANGUAGE.getKey()) .setName(ruleProfileWithoutRule.getName()) .setRulesProfileUuid(ruleProfileWithoutRule.getUuid()); QProfileDto qProfileLongNameWithoutRule = newQualityProfileDto() .setIsBuiltIn(true) .setName(ruleProfileLongNameWithoutRule.getName()) .setLanguage(FOO_LANGUAGE.getKey()) .setRulesProfileUuid(ruleProfileLongNameWithoutRule.getUuid()); QProfileDto qProfileWithOneRule = newQualityProfileDto() .setIsBuiltIn(true) .setName(ruleProfileWithOneRule.getName()) .setLanguage(FOO_LANGUAGE.getKey()) .setRulesProfileUuid(ruleProfileWithOneRule.getUuid()); QProfileDto qProfileWithOneRuleToBeRenamed = newQualityProfileDto() .setIsBuiltIn(true) .setName(ruleProfileWithOneRuleToBeRenamed.getName()) .setLanguage(FOO_LANGUAGE.getKey()) .setRulesProfileUuid(ruleProfileWithOneRuleToBeRenamed.getUuid()); db.qualityProfiles().insert(qProfileWithoutRule, qProfileWithOneRule, qProfileLongNameWithoutRule, qProfileWithOneRuleToBeRenamed); RuleDto ruleDto = db.rules().insert(); db.qualityProfiles().activateRule(qProfileWithOneRule, ruleDto); db.qualityProfiles().activateRule(qProfileWithOneRuleToBeRenamed, ruleDto); db.commit(); // adding only one profile as the other does not exist in plugins builtInQProfileRepositoryRule.add(FOO_LANGUAGE, ruleProfileWithOneRule.getName(), true); builtInQProfileRepositoryRule.initialize(); underTest.start(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd yyyy 'at' hh:mm a") .withLocale(Locale.getDefault()) .withZone(ZoneId.systemDefault()); var expectedSuffix = " (outdated copy since " + formatter.format(Instant.ofEpochMilli(system2.now())) + ")"; assertThat(logTester.logs(Level.INFO)).contains( format("Quality profile [%s] for language [%s] is no longer built-in and has been renamed to [%s] " + "since it does not have any active rules.", qProfileWithoutRule.getName(), qProfileWithoutRule.getLanguage(), qProfileWithoutRule.getName() + expectedSuffix), format("Quality profile [%s] for language [%s] is no longer built-in and has been renamed to [%s] " + "since it does not have any active rules.", qProfileLongNameWithoutRule.getName(), qProfileLongNameWithoutRule.getLanguage(), "That's a very very very very very ver..." + expectedSuffix), format("Quality profile [%s] for language [%s] is no longer built-in and has been renamed to [%s] " + "since it does not have any active rules.", qProfileWithOneRuleToBeRenamed.getName(), qProfileWithOneRuleToBeRenamed.getLanguage(), qProfileWithOneRuleToBeRenamed.getName() + expectedSuffix)); assertThat(dbClient.qualityProfileDao().selectByUuid(db.getSession(), qProfileWithoutRule.getKee())) .extracting(QProfileDto::isBuiltIn, QProfileDto::getName) .containsExactly(false, qProfileWithoutRule.getName() + expectedSuffix); assertThat(dbClient.qualityProfileDao().selectByUuid(db.getSession(), qProfileLongNameWithoutRule.getKee())) .extracting(QProfileDto::isBuiltIn, QProfileDto::getName) .containsExactly(false, "That's a very very very very very ver..." + expectedSuffix); assertThat(dbClient.qualityProfileDao().selectByUuid(db.getSession(), qProfileWithOneRuleToBeRenamed.getKee())) .extracting(QProfileDto::isBuiltIn, QProfileDto::getName) .containsExactly(false, qProfileWithOneRuleToBeRenamed.getName() + expectedSuffix); // the other profile did not change assertThat(dbClient.qualityProfileDao().selectByUuid(db.getSession(), qProfileWithOneRule.getKee())) .extracting(QProfileDto::isBuiltIn, QProfileDto::getName) .containsExactly(true, qProfileWithOneRule.getName()); } private Optional<String> selectUuidOfDefaultProfile(String language) { return db.select("select qprofile_uuid as \"profileUuid\" " + " from default_qprofiles " + " where language='" + language + "'") .stream() .findFirst() .map(m -> (String) m.get("profileUuid")); } private String selectPersistedName(QProfileDto profile) { return db.qualityProfiles().selectByUuid(profile.getKee()).get().getName(); } private void insertRulesProfile(BuiltInQProfile builtIn) { RulesProfileDto dto = newRuleProfileDto(rp -> rp .setIsBuiltIn(true) .setLanguage(builtIn.getLanguage()) .setName(builtIn.getName())); dbClient.qualityProfileDao().insert(db.getSession(), dto); db.commit(); } private static class DummyBuiltInQProfileInsert implements BuiltInQProfileInsert { private final List<BuiltInQProfile> callLogs = new ArrayList<>(); @Override public void create(DbSession batchDbSession, BuiltInQProfile builtIn) { callLogs.add(builtIn); } } private static class DummyBuiltInQProfileUpdate implements BuiltInQProfileUpdate { private final List<BuiltInQProfile> callLogs = new ArrayList<>(); @Override public List<ActiveRuleChange> update(DbSession dbSession, BuiltInQProfile builtIn, RulesProfileDto ruleProfile) { callLogs.add(builtIn); return Collections.emptyList(); } } }
13,910
45.215947
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/it/java/org/sonar/server/qualityprofile/RegisterQualityProfilesNotificationIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.qualityprofile; import com.google.common.collect.Multimap; import java.security.SecureRandom; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RulePriority; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInActiveRule; import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.qualityprofile.RulesProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventService; import org.sonar.server.qualityprofile.builtin.BuiltInQProfile; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsert; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsertImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileRepositoryRule; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdate; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdateImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQualityProfilesUpdateListener; import org.sonar.server.qualityprofile.builtin.QProfileName; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.DefaultRuleFinder; import org.sonar.server.rule.RuleDescriptionFormatter; import org.sonar.server.rule.ServerRuleFinder; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.util.TypeValidations; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.RandomUtils.nextLong; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.rules.RulePriority.MAJOR; import static org.sonar.db.qualityprofile.QualityProfileTesting.newRuleProfileDto; import static org.sonar.server.language.LanguageTesting.newLanguage; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.ACTIVATED; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.DEACTIVATED; import static org.sonar.server.qualityprofile.ActiveRuleChange.Type.UPDATED; public class RegisterQualityProfilesNotificationIT { private static final Random RANDOM = new SecureRandom(); private System2 system2 = mock(System2.class); @Rule public DbTester db = DbTester.create(system2); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); @Rule public BuiltInQProfileRepositoryRule builtInQProfileRepositoryRule = new BuiltInQProfileRepositoryRule(); @Rule public LogTester logTester = new LogTester(); private DbClient dbClient = db.getDbClient(); private TypeValidations typeValidations = mock(TypeValidations.class); private ActiveRuleIndexer activeRuleIndexer = mock(ActiveRuleIndexer.class); private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class); private ServerRuleFinder ruleFinder = new DefaultRuleFinder(dbClient, mock(RuleDescriptionFormatter.class)); private BuiltInQProfileInsert builtInQProfileInsert = new BuiltInQProfileInsertImpl(dbClient, ruleFinder, system2, UuidFactoryFast.getInstance(), typeValidations, activeRuleIndexer); private RuleActivator ruleActivator = new RuleActivator(system2, dbClient, typeValidations, userSessionRule); private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, mock(RuleIndex.class), activeRuleIndexer, qualityProfileChangeEventService); private BuiltInQProfileUpdate builtInQProfileUpdate = new BuiltInQProfileUpdateImpl(dbClient, ruleActivator, activeRuleIndexer, qualityProfileChangeEventService); private BuiltInQualityProfilesUpdateListener builtInQualityProfilesNotification = mock(BuiltInQualityProfilesUpdateListener.class); private RegisterQualityProfiles underTest = new RegisterQualityProfiles(builtInQProfileRepositoryRule, dbClient, builtInQProfileInsert, builtInQProfileUpdate, builtInQualityProfilesNotification, system2); @Test public void do_not_send_notification_on_new_profile() { String language = newLanguageKey(); builtInQProfileRepositoryRule.add(newLanguage(language), "Sonar way"); builtInQProfileRepositoryRule.initialize(); underTest.start(); verifyNoInteractions(builtInQualityProfilesNotification); } @Test public void do_not_send_notification_when_profile_is_not_updated() { String language = newLanguageKey(); RuleDto dbRule = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile = insertBuiltInProfile(language); activateRuleInDb(dbProfile, dbRule, MAJOR); addPluginProfile(dbProfile, dbRule); builtInQProfileRepositoryRule.initialize(); underTest.start(); verifyNoInteractions(builtInQualityProfilesNotification); } @Test public void send_notification_when_a_new_rule_is_activated() { String language = newLanguageKey(); RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile = insertBuiltInProfile(language); activateRuleInDb(dbProfile, existingRule, MAJOR); RuleDto newRule = db.rules().insert(r -> r.setLanguage(language)); addPluginProfile(dbProfile, existingRule, newRule); builtInQProfileRepositoryRule.initialize(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder(tuple(dbProfile.getName(), dbProfile.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(newRule.getUuid(), ACTIVATED)); } @Test public void send_notification_when_a_rule_is_deactivated() { String language = newLanguageKey(); RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile = insertBuiltInProfile(language); activateRuleInDb(dbProfile, existingRule, MAJOR); addPluginProfile(dbProfile); builtInQProfileRepositoryRule.initialize(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder(tuple(dbProfile.getName(), dbProfile.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(existingRule.getUuid(), DEACTIVATED)); } @Test public void send_a_single_notification_when_multiple_rules_are_activated() { String language = newLanguageKey(); RuleDto existingRule1 = db.rules().insert(r -> r.setLanguage(language)); RuleDto newRule1 = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile1 = insertBuiltInProfile(language); activateRuleInDb(dbProfile1, existingRule1, MAJOR); addPluginProfile(dbProfile1, existingRule1, newRule1); RuleDto existingRule2 = db.rules().insert(r -> r.setLanguage(language)); RuleDto newRule2 = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile2 = insertBuiltInProfile(language); activateRuleInDb(dbProfile2, existingRule2, MAJOR); addPluginProfile(dbProfile2, existingRule2, newRule2); builtInQProfileRepositoryRule.initialize(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder( tuple(dbProfile1.getName(), dbProfile1.getLanguage()), tuple(dbProfile2.getName(), dbProfile2.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder( tuple(newRule1.getUuid(), ACTIVATED), tuple(newRule2.getUuid(), ACTIVATED)); } @Test public void notification_does_not_include_inherited_profiles_when_rule_is_added() { String language = newLanguageKey(); RuleDto newRule = db.rules().insert(r -> r.setLanguage(language)); QProfileDto builtInQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language)); QProfileDto childQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(false).setLanguage(language).setParentKee(builtInQProfileDto.getKee())); addPluginProfile(builtInQProfileDto, newRule); builtInQProfileRepositoryRule.initialize(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder(tuple(builtInQProfileDto.getName(), builtInQProfileDto.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(newRule.getUuid(), ACTIVATED)); } @Test public void notification_does_not_include_inherited_profiled_when_rule_is_changed() { String language = newLanguageKey(); RuleDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR)); QProfileDto builtInProfile = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language)); db.qualityProfiles().activateRule(builtInProfile, rule, ar -> ar.setSeverity(Severity.MINOR)); QProfileDto childProfile = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(false).setLanguage(language).setParentKee(builtInProfile.getKee())); db.qualityProfiles().activateRule(childProfile, rule, ar -> ar.setInheritance(ActiveRuleDto.INHERITED).setSeverity(Severity.MINOR)); addPluginProfile(builtInProfile, rule); builtInQProfileRepositoryRule.initialize(); db.commit(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder(tuple(builtInProfile.getName(), builtInProfile.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(rule.getUuid(), UPDATED)); } @Test public void notification_does_not_include_inherited_profiles_when_rule_is_deactivated() { String language = newLanguageKey(); RuleDto rule = db.rules().insert(r -> r.setLanguage(language).setSeverity(Severity.MINOR)); QProfileDto builtInQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(true).setLanguage(language)); db.qualityProfiles().activateRule(builtInQProfileDto, rule); QProfileDto childQProfileDto = insertProfile(orgQProfile -> orgQProfile.setIsBuiltIn(false).setLanguage(language).setParentKee(builtInQProfileDto.getKee())); qProfileRules.activateAndCommit(db.getSession(), childQProfileDto, singleton(RuleActivation.create(rule.getUuid()))); db.commit(); addPluginProfile(builtInQProfileDto); builtInQProfileRepositoryRule.initialize(); underTest.start(); ArgumentCaptor<Multimap> captor = ArgumentCaptor.forClass(Multimap.class); verify(builtInQualityProfilesNotification).onChange(captor.capture(), anyLong(), anyLong()); Multimap<QProfileName, ActiveRuleChange> updatedProfiles = captor.getValue(); assertThat(updatedProfiles.keySet()) .extracting(QProfileName::getName, QProfileName::getLanguage) .containsExactlyInAnyOrder(tuple(builtInQProfileDto.getName(), builtInQProfileDto.getLanguage())); assertThat(updatedProfiles.values()) .extracting(value -> value.getActiveRule().getRuleUuid(), ActiveRuleChange::getType) .containsExactlyInAnyOrder(tuple(rule.getUuid(), DEACTIVATED)); } @Test public void notification_contains_send_start_and_end_date() { String language = newLanguageKey(); RuleDto existingRule = db.rules().insert(r -> r.setLanguage(language)); RulesProfileDto dbProfile = insertBuiltInProfile(language); activateRuleInDb(dbProfile, existingRule, MAJOR); RuleDto newRule = db.rules().insert(r -> r.setLanguage(language)); addPluginProfile(dbProfile, existingRule, newRule); builtInQProfileRepositoryRule.initialize(); long startDate = RANDOM.nextInt(5000); long endDate = startDate + RANDOM.nextInt(5000); when(system2.now()).thenReturn(startDate, endDate); underTest.start(); verify(builtInQualityProfilesNotification).onChange(any(), eq(startDate), eq(endDate)); } private void addPluginProfile(RulesProfileDto dbProfile, RuleDto... dbRules) { BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(dbProfile.getName(), dbProfile.getLanguage()); Arrays.stream(dbRules).forEach(dbRule -> newQp.activateRule(dbRule.getRepositoryKey(), dbRule.getRuleKey()).overrideSeverity(Severity.MAJOR)); newQp.done(); List<BuiltInActiveRule> rules = context.profile(dbProfile.getLanguage(), dbProfile.getName()).rules(); BuiltInQProfile.ActiveRule[] activeRules = toActiveRules(rules, dbRules); builtInQProfileRepositoryRule.add(newLanguage(dbProfile.getLanguage()), dbProfile.getName(), false, activeRules); } private static BuiltInQProfile.ActiveRule[] toActiveRules(List<BuiltInActiveRule> rules, RuleDto[] dbRules) { Map<RuleKey, RuleDto> dbRulesByRuleKey = Arrays.stream(dbRules) .collect(Collectors.toMap(RuleDto::getKey, Function.identity())); return rules.stream() .map(r -> { RuleKey ruleKey = RuleKey.of(r.repoKey(), r.ruleKey()); RuleDto ruleDefinitionDto = dbRulesByRuleKey.get(ruleKey); checkState(ruleDefinitionDto != null, "Rule '%s' not found", ruleKey); return new BuiltInQProfile.ActiveRule(ruleDefinitionDto.getUuid(), r); }).toArray(BuiltInQProfile.ActiveRule[]::new); } private void addPluginProfile(QProfileDto profile, RuleDto... dbRules) { BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); NewBuiltInQualityProfile newQp = context.createBuiltInQualityProfile(profile.getName(), profile.getLanguage()); Arrays.stream(dbRules).forEach(dbRule -> newQp.activateRule(dbRule.getRepositoryKey(), dbRule.getRuleKey()).overrideSeverity(Severity.MAJOR)); newQp.done(); BuiltInQProfile.ActiveRule[] activeRules = toActiveRules(context.profile(profile.getLanguage(), profile.getName()).rules(), dbRules); builtInQProfileRepositoryRule.add(newLanguage(profile.getLanguage()), profile.getName(), false, activeRules); } private RulesProfileDto insertBuiltInProfile(String language) { RulesProfileDto ruleProfileDto = newRuleProfileDto(rp -> rp.setIsBuiltIn(true).setLanguage(language)); db.getDbClient().qualityProfileDao().insert(db.getSession(), ruleProfileDto); db.commit(); return ruleProfileDto; } private void activateRuleInDb(RulesProfileDto profile, RuleDto rule, RulePriority severity) { ActiveRuleDto dto = new ActiveRuleDto() .setProfileUuid(profile.getUuid()) .setSeverity(severity.name()) .setRuleUuid(rule.getUuid()) .setCreatedAt(nextLong()) .setUpdatedAt(nextLong()); db.getDbClient().activeRuleDao().insert(db.getSession(), dto); db.commit(); } private QProfileDto insertProfile(Consumer<QProfileDto> consumer) { QProfileDto builtInQProfileDto = db.qualityProfiles().insert(consumer); db.commit(); return builtInQProfileDto; } private static String newLanguageKey() { return randomAlphanumeric(20).toLowerCase(); } }
19,032
49.890374
164
java