import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentQuery;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.component.ComponentCleanerService;
import org.sonar.server.project.Project;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
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_ORGANIZATION;
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;
private final ComponentCleanerService componentCleanerService;
private final DbClient dbClient;
private final UserSession userSession;
- private final ProjectsWsSupport support;
private final ProjectLifeCycleListeners projectLifeCycleListeners;
public BulkDeleteAction(ComponentCleanerService componentCleanerService, DbClient dbClient, UserSession userSession,
- ProjectsWsSupport support, ProjectLifeCycleListeners projectLifeCycleListeners) {
+ ProjectLifeCycleListeners projectLifeCycleListeners) {
this.componentCleanerService = componentCleanerService;
this.dbClient = dbClient;
this.userSession = userSession;
- this.support = support;
this.projectLifeCycleListeners = projectLifeCycleListeners;
}
.setHandler(this)
.setChangelog(new Change("7.8", parameterRequiredMessage));
- support.addOrganizationParam(action);
-
action
.createParam(PARAM_PROJECTS)
.setDescription("Comma-separated list of project keys")
action.createParam(PARAM_VISIBILITY)
.setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
- "If no visibility is specified, the default project visibility of the organization will be used.",
+ "If no visibility is specified, the default project visibility will be used.",
Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
.setRequired(false)
.setInternal(true)
SearchRequest searchRequest = toSearchWsRequest(request);
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
- OrganizationDto organization = support.getOrganization(dbSession, searchRequest.getOrganization());
userSession.checkPermission(GlobalPermission.ADMINISTER);
checkAtLeastOneParameterIsPresent(searchRequest);
ComponentQuery query = buildDbQuery(searchRequest);
- Set<ComponentDto> componentDtos = new HashSet<>(dbClient.componentDao().selectByQuery(dbSession, organization.getUuid(), query, 0, Integer.MAX_VALUE));
+ Set<ComponentDto> componentDtos = new HashSet<>(dbClient.componentDao().selectByQuery(dbSession, query, 0, Integer.MAX_VALUE));
try {
componentDtos.forEach(p -> componentCleanerService.delete(dbSession, p));
private static SearchRequest toSearchWsRequest(Request request) {
return SearchRequest.builder()
- .setOrganization(request.param(PARAM_ORGANIZATION))
.setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
.setQuery(request.param(Param.TEXT_QUERY))
.setVisibility(request.param(PARAM_VISIBILITY))
import static org.sonar.db.component.ComponentValidator.MAX_COMPONENT_NAME_LENGTH;
import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
import static org.sonar.server.component.NewComponent.newComponentBuilder;
-import static org.sonar.server.project.ws.ProjectsWsSupport.PARAM_ORGANIZATION;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_CREATE;
public class CreateAction implements ProjectsWsAction {
- private final ProjectsWsSupport support;
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentUpdater componentUpdater;
private final ProjectDefaultVisibility projectDefaultVisibility;
- public CreateAction(ProjectsWsSupport support, DbClient dbClient, UserSession userSession, ComponentUpdater componentUpdater,
+ public CreateAction(DbClient dbClient, UserSession userSession, ComponentUpdater componentUpdater,
ProjectDefaultVisibility projectDefaultVisibility) {
- this.support = support;
this.dbClient = dbClient;
this.userSession = userSession;
this.componentUpdater = componentUpdater;
action.createParam(PARAM_VISIBILITY)
.setDescription("Whether the created project should be visible to everyone, or only specific user/groups.<br/>" +
- "If no visibility is specified, the default project visibility of the organization will be used.")
+ "If no visibility is specified, the default project visibility will be used.")
.setRequired(false)
.setSince("6.4")
.setPossibleValues(Visibility.getLabels());
- support.addOrganizationParam(action);
}
@Override
private static CreateRequest toCreateRequest(Request request) {
return CreateRequest.builder()
- .setOrganization(request.param(PARAM_ORGANIZATION))
.setProjectKey(request.mandatoryParam(PARAM_PROJECT))
.setName(abbreviate(request.mandatoryParam(PARAM_NAME), MAX_COMPONENT_NAME_LENGTH))
.setVisibility(request.param(PARAM_VISIBILITY))
}
static class CreateRequest {
-
- private final String organization;
private final String projectKey;
private final String name;
@CheckForNull
private final String visibility;
private CreateRequest(Builder builder) {
- this.organization = builder.organization;
this.projectKey = builder.projectKey;
this.name = builder.name;
this.visibility = builder.visibility;
}
- @CheckForNull
- public String getOrganization() {
- return organization;
- }
-
public String getProjectKey() {
return projectKey;
}
}
static class Builder {
- private String organization;
private String projectKey;
private String name;
@CheckForNull
private Builder() {
}
- public Builder setOrganization(@Nullable String organization) {
- this.organization = organization;
- return this;
- }
-
public Builder setProjectKey(String projectKey) {
requireNonNull(projectKey);
this.projectKey = projectKey;
add(
ProjectDefaultVisibility.class,
ProjectLifeCycleListenersImpl.class,
- ProjectsWsSupport.class,
ProjectsWs.class,
CreateAction.class,
BulkDeleteAction.class,
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2020 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 javax.annotation.Nullable;
-import org.sonar.api.server.ServerSide;
-import org.sonar.api.server.ws.WebService;
-import org.sonar.db.DbClient;
-import org.sonar.db.DbSession;
-import org.sonar.db.organization.OrganizationDto;
-import org.sonar.server.organization.DefaultOrganizationProvider;
-
-import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional;
-
-@ServerSide
-public class ProjectsWsSupport {
- public static final String PARAM_ORGANIZATION = "organization";
-
- private final DbClient dbClient;
- private final DefaultOrganizationProvider organizationProvider;
-
- public ProjectsWsSupport(DbClient dbClient, DefaultOrganizationProvider organizationProvider) {
- this.dbClient = dbClient;
- this.organizationProvider = organizationProvider;
- }
-
- void addOrganizationParam(WebService.NewAction action) {
- action.createParam(PARAM_ORGANIZATION)
- .setDescription("The key of the organization")
- .setRequired(false)
- .setInternal(true)
- .setSince("6.3");
- }
-
- OrganizationDto getOrganization(DbSession dbSession, @Nullable String organizationKeyParam) {
- String organizationKey = organizationKeyParam == null ? organizationProvider.get().getKey() : organizationKeyParam;
- return checkFoundWithOptional(
- dbClient.organizationDao().selectByKey(dbSession, organizationKey),
- "No organization for key '%s'", organizationKey);
- }
-
-}
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentQuery;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Projects.SearchWsResponse;
-import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Optional.ofNullable;
import static java.util.function.Function.identity;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.MAX_PAGE_SIZE;
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_ORGANIZATION;
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;
private final DbClient dbClient;
private final UserSession userSession;
- private final ProjectsWsSupport support;
- public SearchAction(DbClient dbClient, UserSession userSession, ProjectsWsSupport support) {
+ public SearchAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
- this.support = support;
}
@Override
.setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers")
.setPossibleValues(PROJECT, VIEW, APP)
.setDefaultValue(PROJECT);
- support.addOrganizationParam(action);
action.createParam(PARAM_VISIBILITY)
.setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
- "If no visibility is specified, the default project visibility of the organization will be used.",
+ "If no visibility is specified, the default project visibility will be used.",
Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
.setRequired(false)
.setInternal(true)
private static SearchRequest toSearchWsRequest(Request request) {
return SearchRequest.builder()
- .setOrganization(request.param(PARAM_ORGANIZATION))
.setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
.setQuery(request.param(Param.TEXT_QUERY))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
private SearchWsResponse doHandle(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
- OrganizationDto organization = support.getOrganization(dbSession, request.getOrganization());
userSession.checkPermission(GlobalPermission.ADMINISTER);
ComponentQuery query = buildDbQuery(request);
- Paging paging = buildPaging(dbSession, request, organization, query);
- List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, organization.getUuid(), query, paging.offset(), paging.pageSize());
+ Paging paging = buildPaging(dbSession, request, query);
+ List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, query, paging.offset(), paging.pageSize());
Set<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(MoreCollectors.toHashSet(components.size()));
Map<String, SnapshotDto> snapshotsByComponentUuid = dbClient.snapshotDao()
.selectLastAnalysesByRootComponentUuids(dbSession, componentUuids).stream()
.collect(MoreCollectors.uniqueIndex(SnapshotDto::getComponentUuid, identity()));
- return buildResponse(components, organization, snapshotsByComponentUuid, paging);
+ return buildResponse(components, snapshotsByComponentUuid, paging);
}
}
return query.build();
}
- private Paging buildPaging(DbSession dbSession, SearchRequest request, OrganizationDto organization, ComponentQuery query) {
- int total = dbClient.componentDao().countByQuery(dbSession, organization.getUuid(), query);
+ private Paging buildPaging(DbSession dbSession, SearchRequest request, ComponentQuery query) {
+ int total = dbClient.componentDao().countByQuery(dbSession, query);
return Paging.forPageIndex(request.getPage())
.withPageSize(request.getPageSize())
.andTotal(total);
}
- private static SearchWsResponse buildResponse(List<ComponentDto> components, OrganizationDto organization, Map<String, SnapshotDto> snapshotsByComponentUuid, Paging paging) {
+ private static SearchWsResponse buildResponse(List<ComponentDto> components, Map<String, SnapshotDto> snapshotsByComponentUuid, Paging paging) {
SearchWsResponse.Builder responseBuilder = newBuilder();
responseBuilder.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.build();
components.stream()
- .map(dto -> dtoToProject(organization, dto, snapshotsByComponentUuid.get(dto.uuid())))
+ .map(dto -> dtoToProject(dto, snapshotsByComponentUuid.get(dto.uuid())))
.forEach(responseBuilder::addComponents);
return responseBuilder.build();
}
- private static Component dtoToProject(OrganizationDto organization, ComponentDto dto, @Nullable SnapshotDto snapshot) {
- checkArgument(
- organization.getUuid().equals(dto.getOrganizationUuid()),
- "No Organization found for uuid '%s'",
- dto.getOrganizationUuid());
-
+ private static Component dtoToProject(ComponentDto dto, @Nullable SnapshotDto snapshot) {
Component.Builder builder = Component.newBuilder()
- .setOrganization(organization.getKey())
.setKey(dto.getDbKey())
.setName(dto.name())
.setQualifier(dto.qualifier())
class SearchRequest {
- private final String organization;
private final String query;
private final List<String> qualifiers;
private final String visibility;
private final List<String> projects;
public SearchRequest(Builder builder) {
- this.organization = builder.organization;
this.query = builder.query;
this.qualifiers = builder.qualifiers;
this.visibility = builder.visibility;
this.projects = builder.projects;
}
- @CheckForNull
- public String getOrganization() {
- return organization;
- }
-
public List<String> getQualifiers() {
return qualifiers;
}
}
public static class Builder {
- private String organization;
private List<String> qualifiers = singletonList(Qualifiers.PROJECT);
private Integer page;
private Integer pageSize;
private boolean onProvisionedOnly = false;
private List<String> projects;
- public Builder setOrganization(@Nullable String organization) {
- this.organization = organization;
- return this;
- }
-
public Builder setQualifiers(List<String> qualifiers) {
this.qualifiers = requireNonNull(qualifiers, "Qualifiers cannot be null");
return this;
}
public SearchRequest build() {
- checkArgument(projects==null || !projects.isEmpty(), "Project key list must not be empty");
+ checkArgument(projects == null || !projects.isEmpty(), "Project key list must not be empty");
checkArgument(pageSize == null || pageSize <= MAX_PAGE_SIZE, "Page size must not be greater than %s", MAX_PAGE_SIZE);
return new SearchRequest(this);
}
},
"components": [
{
- "organization": "my-org-1",
"key": "project-key-1",
"name": "Project Name 1",
"qualifier": "TRK",
"revision": "cfb82f55c6ef32e61828c4cb3db2da12795fd767"
},
{
- "organization": "my-org-1",
"key": "project-key-2",
"name": "Project Name 1",
"qualifier": "TRK",
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentCleanerService;
-import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.UnauthorizedException;
-import org.sonar.server.organization.TestDefaultOrganizationProvider;
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.verifyZeroInteractions;
+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_ORGANIZATION;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
public class BulkDeleteActionTest {
@Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
+ public final DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSession = UserSessionRule.standalone();
private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
private final DbClient dbClient = db.getDbClient();
- private final ProjectsWsSupport support = new ProjectsWsSupport(dbClient, TestDefaultOrganizationProvider.from(db));
private final ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class);
- private final BulkDeleteAction underTest = new BulkDeleteAction(componentCleanerService, dbClient, userSession, support, projectLifeCycleListeners);
+ private final BulkDeleteAction underTest = new BulkDeleteAction(componentCleanerService, dbClient, userSession, projectLifeCycleListeners);
private final WsActionTester ws = new WsActionTester(underTest);
- private OrganizationDto org1;
- private OrganizationDto org2;
-
- @Before
- public void setUp() {
- org1 = db.organizations().insert();
- org2 = db.organizations().insert();
- }
-
@Test
- public void delete_projects_in_default_organization_if_no_org_provided() {
+ public void delete_projects() {
userSession.logIn().setRoot();
- OrganizationDto defaultOrganization = db.getDefaultOrganization();
- ComponentDto toDeleteInOrg1 = db.components().insertPrivateProject(org1);
- ComponentDto toDeleteInOrg2 = db.components().insertPrivateProject(defaultOrganization);
- ComponentDto toKeep = db.components().insertPrivateProject(defaultOrganization);
+ ComponentDto project1ToDelete = db.components().insertPrivateProject();
+ ComponentDto project2ToDelete = db.components().insertPrivateProject();
+ ComponentDto toKeep = db.components().insertPrivateProject();
TestResponse result = ws.newRequest()
- .setParam(PARAM_PROJECTS, toDeleteInOrg1.getDbKey() + "," + toDeleteInOrg2.getDbKey())
+ .setParam(PARAM_PROJECTS, project1ToDelete.getDbKey() + "," + project2ToDelete.getDbKey())
.execute();
assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT);
assertThat(result.getInput()).isEmpty();
- verifyComponentDeleted(toDeleteInOrg2);
- verifyListenersOnProjectsDeleted(toDeleteInOrg2);
+ verifyComponentDeleted(project1ToDelete, project2ToDelete);
+ verifyListenersOnProjectsDeleted(project1ToDelete, project2ToDelete);
}
@Test
public void delete_projects_by_keys() {
userSession.logIn().setRoot();
- ComponentDto toDeleteInOrg1 = db.components().insertPrivateProject(org1);
- ComponentDto toDeleteInOrg2 = db.components().insertPrivateProject(org1);
- ComponentDto toKeep = db.components().insertPrivateProject(org1);
+ ComponentDto toDeleteInOrg1 = db.components().insertPrivateProject();
+ ComponentDto toDeleteInOrg2 = db.components().insertPrivateProject();
+ ComponentDto toKeep = db.components().insertPrivateProject();
ws.newRequest()
- .setParam(PARAM_ORGANIZATION, org1.getKey())
.setParam(PARAM_PROJECTS, toDeleteInOrg1.getDbKey() + "," + toDeleteInOrg2.getDbKey())
.execute();
@Test
public void throw_IllegalArgumentException_if_request_without_any_parameters() {
userSession.logIn().setRoot();
- db.components().insertPrivateProject(org1);
-
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("At lease one parameter among analyzedBefore, projects and q must be provided");
+ db.components().insertPrivateProject();
try {
- ws.newRequest().execute();
+ TestRequest request = ws.newRequest();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("At lease one parameter among analyzedBefore, projects and q must be provided");
} finally {
verifyNoDeletions();
- verifyZeroInteractions(projectLifeCycleListeners);
+ verifyNoMoreInteractions(projectLifeCycleListeners);
}
}
@Test
public void projects_that_dont_exist_are_ignored_and_dont_break_bulk_deletion() {
userSession.logIn().setRoot();
- ComponentDto toDelete1 = db.components().insertPrivateProject(org1);
- ComponentDto toDelete2 = db.components().insertPrivateProject(org1);
+ ComponentDto toDelete1 = db.components().insertPrivateProject();
+ ComponentDto toDelete2 = db.components().insertPrivateProject();
ws.newRequest()
- .setParam("organization", org1.getKey())
.setParam("projects", toDelete1.getDbKey() + ",missing," + toDelete2.getDbKey() + ",doesNotExist")
.execute();
public void delete_only_the_1000_first_projects() {
userSession.logIn().addPermission(ADMINISTER);
List<String> keys = IntStream.range(0, 1_010).mapToObj(i -> "key" + i).collect(MoreCollectors.toArrayList());
- keys.forEach(key -> db.components().insertPrivateProject(org1, p -> p.setDbKey(key)));
+ keys.forEach(key -> db.components().insertPrivateProject(p -> p.setDbKey(key)));
ws.newRequest()
- .setParam("organization", org1.getKey())
.setParam("projects", StringUtils.join(keys, ","))
.execute();
@Test
public void projectLifeCycleListeners_onProjectsDeleted_called_even_if_delete_fails() {
userSession.logIn().addPermission(ADMINISTER);
- ComponentDto project1 = db.components().insertPrivateProject(org1);
- ComponentDto project2 = db.components().insertPrivateProject(org1);
- ComponentDto project3 = db.components().insertPrivateProject(org1);
+ ComponentDto project1 = db.components().insertPrivateProject();
+ ComponentDto project2 = db.components().insertPrivateProject();
+ ComponentDto project3 = db.components().insertPrivateProject();
ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
RuntimeException expectedException = new RuntimeException("Faking delete failing on 2nd project");
doNothing()
try {
ws.newRequest()
- .setParam("organization", org1.getKey())
.setParam("projects", project1.getDbKey() + "," + project2.getDbKey() + "," + project3.getDbKey())
.execute();
} catch (RuntimeException e) {
}
@Test
- public void organization_administrator_deletes_projects_by_keys_in_his_organization() {
+ public void global_administrator_deletes_projects_by_keys() {
userSession.logIn().addPermission(ADMINISTER);
- ComponentDto toDelete = db.components().insertPrivateProject(org1);
- ComponentDto cantBeDeleted = db.components().insertPrivateProject(org2);
+ ComponentDto toDelete1 = db.components().insertPrivateProject();
+ ComponentDto toDelete2 = db.components().insertPrivateProject();
ws.newRequest()
- .setParam("organization", org1.getKey())
- .setParam("projects", toDelete.getDbKey() + "," + cantBeDeleted.getDbKey())
+ .setParam("projects", toDelete1.getDbKey() + "," + toDelete2.getDbKey())
.execute();
- verifyComponentDeleted(toDelete);
- verifyListenersOnProjectsDeleted(toDelete);
+ verifyComponentDeleted(toDelete1, toDelete2);
+ verifyListenersOnProjectsDeleted(toDelete1, toDelete2);
}
@Test
public void throw_UnauthorizedException_if_not_logged_in() {
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- ws.newRequest()
- .setParam("ids", "whatever-the-uuid").execute();
+ TestRequest request = ws.newRequest().setParam("ids", "whatever-the-uuid");
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(UnauthorizedException.class)
+ .hasMessage("Authentication is required");
verifyNoDeletions();
- verifyZeroInteractions(projectLifeCycleListeners);
- }
-
- @Test
- public void throw_ForbiddenException_if_param_organization_is_not_set_and_not_system_administrator() {
- userSession.logIn().setNonSystemAdministrator();
-
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- ws.newRequest()
- .setParam("ids", "whatever-the-uuid").execute();
-
- verifyNoDeletions();
- verifyZeroInteractions(projectLifeCycleListeners);
- }
-
- @Test
- public void throw_ForbiddenException_if_param_organization_is_set_but_not_organization_administrator() {
- userSession.logIn();
-
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- ws.newRequest()
- .setParam("organization", org1.getKey())
- .setParam("ids", "whatever-the-uuid")
- .execute();
-
- verifyNoDeletions();
- verifyZeroInteractions(projectLifeCycleListeners);
- }
-
- private void verifyProjectDeleted(ComponentDto... projects) {
- ArgumentCaptor<ProjectDto> argument = ArgumentCaptor.forClass(ProjectDto.class);
- verify(componentCleanerService, times(projects.length)).delete(any(DbSession.class), argument.capture());
-
- for (ComponentDto project : projects) {
- assertThat(argument.getAllValues()).extracting(ProjectDto::getUuid).contains(project.uuid());
- }
+ verifyNoMoreInteractions(projectLifeCycleListeners);
}
private void verifyComponentDeleted(ComponentDto... projects) {
}
private void verifyNoDeletions() {
- verifyZeroInteractions(componentCleanerService);
+ verifyNoMoreInteractions(componentCleanerService);
}
private void verifyListenersOnProjectsDeleted(ComponentDto... components) {
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.component.ComponentService;
import org.sonar.server.component.TestComponentFinder;
@Test
public void json_example() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto project = componentDb.insertPrivateProject(organizationDto, c -> c.setDbKey("my_project"));
+ ComponentDto project = componentDb.insertPrivateProject(c -> c.setDbKey("my_project"));
componentDb.insertComponent(newModuleDto(project).setDbKey("my_project:module_1"));
- ComponentDto anotherProject = componentDb.insertPrivateProject(organizationDto, c -> c.setDbKey("another_project"));
+ ComponentDto anotherProject = componentDb.insertPrivateProject(c -> c.setDbKey("another_project"));
componentDb.insertComponent(newModuleDto(anotherProject).setDbKey("my_new_project:module_1"));
ComponentDto module2 = componentDb.insertComponent(newModuleDto(project).setDbKey("my_project:module_2"));
componentDb.insertComponent(newFileDto(module2, null));
@Test
public void fail_to_bulk_if_a_component_already_exists_with_the_same_key() {
- componentDb.insertPrivateProject(db.getDefaultOrganization(), c -> c.setDbKey("my_project"));
- componentDb.insertPrivateProject(db.getDefaultOrganization(), c -> c.setDbKey("your_project"));
+ componentDb.insertPrivateProject(c -> c.setDbKey("my_project"));
+ componentDb.insertPrivateProject(c -> c.setDbKey("your_project"));
expectedException.expect(BadRequestException.class);
expectedException.expectMessage("Impossible to update key: a component with key \"your_project\" already exists.");
}
private ComponentDto insertMyProject() {
- return componentDb.insertPublicProject(db.organizations().insert(), c -> c.setDbKey(MY_PROJECT_KEY));
+ return componentDb.insertPublicProject(c -> c.setDbKey(MY_PROJECT_KEY));
}
private BulkUpdateKeyWsResponse callDryRunByKey(@Nullable String key, @Nullable String from, @Nullable String to) {
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.es.TestProjectIndexers;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.favorite.FavoriteUpdater;
import org.sonar.server.l18n.I18nRule;
-import org.sonar.server.organization.BillingValidations;
-import org.sonar.server.organization.BillingValidations.BillingValidationsException;
-import org.sonar.server.organization.BillingValidationsProxy;
import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.permission.PermissionTemplateService;
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 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.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
import static org.sonar.server.project.Visibility.PRIVATE;
-import static org.sonar.server.project.ws.ProjectsWsSupport.PARAM_ORGANIZATION;
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_NAME;
private final System2 system2 = System2.INSTANCE;
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final DbTester db = DbTester.create(system2);
@Rule
- public DbTester db = DbTester.create(system2);
+ public final UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
- @Rule
- public I18nRule i18n = new I18nRule().put("qualifier.TRK", "Project");
+ public final I18nRule i18n = new I18nRule().put("qualifier.TRK", "Project");
private final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
- private final BillingValidationsProxy billingValidations = mock(BillingValidationsProxy.class);
private final TestProjectIndexers projectIndexers = new TestProjectIndexers();
private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
private final WsActionTester ws = new WsActionTester(
new CreateAction(
- new ProjectsWsSupport(db.getDbClient(), defaultOrganizationProvider),
db.getDbClient(), userSession,
new ComponentUpdater(db.getDbClient(), i18n, system2, permissionTemplateService, new FavoriteUpdater(db.getDbClient()),
projectIndexers, new SequenceUuidFactory(), defaultOrganizationProvider),
@Test
public void apply_project_visibility_public() {
- OrganizationDto organization = db.organizations().insert();
userSession.addPermission(PROVISION_PROJECTS);
CreateWsResponse result = ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
.setParam("visibility", "public")
.executeProtobuf(CreateWsResponse.class);
@Test
public void apply_project_visibility_private() {
- OrganizationDto organization = db.organizations().insert();
userSession.addPermission(PROVISION_PROJECTS);
CreateWsResponse result = ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
.setParam("visibility", PRIVATE.getLabel())
.executeProtobuf(CreateWsResponse.class);
@Test
public void apply_default_project_visibility_public() {
- OrganizationDto organization = db.organizations().insert();
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)
- .setParam("organization", organization.getKey())
.executeProtobuf(CreateWsResponse.class);
assertThat(result.getProject().getVisibility()).isEqualTo("public");
@Test
public void apply_default_project_visibility_private() {
- OrganizationDto organization = db.organizations().insert();
when(projectDefaultVisibility.get(any())).thenReturn(PRIVATE);
userSession.addPermission(PROVISION_PROJECTS);
CreateWsResponse result = ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
.executeProtobuf(CreateWsResponse.class);
assertThat(result.getProject().getVisibility()).isEqualTo("private");
}
- @Test
- public void does_not_fail_to_create_public_projects_when_organization_is_not_allowed_to_use_private_projects() {
- OrganizationDto organization = db.organizations().insert();
- userSession.addPermission(PROVISION_PROJECTS);
- doThrow(new BillingValidationsException("This organization cannot use project private")).when(billingValidations)
- .checkCanUpdateProjectVisibility(any(BillingValidations.Organization.class), eq(true));
-
- CreateWsResponse result = ws.newRequest()
- .setParam("project", DEFAULT_PROJECT_KEY)
- .setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
- .setParam("visibility", "public")
- .executeProtobuf(CreateWsResponse.class);
-
- assertThat(result.getProject().getVisibility()).isEqualTo("public");
- }
-
@Test
public void abbreviate_project_name_if_very_long() {
- OrganizationDto organization = db.organizations().insert();
userSession.addPermission(PROVISION_PROJECTS);
String longName = Strings.repeat("a", 1_000);
ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", longName)
- .setParam("organization", organization.getKey())
.executeProtobuf(CreateWsResponse.class);
assertThat(db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get().name())
@Test
public void add_project_to_user_favorites_if_project_creator_is_defined_in_permission_template() {
- OrganizationDto organization = db.organizations().insert();
UserDto user = db.users().insertUser();
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
userSession.logIn(user).addPermission(PROVISION_PROJECTS);
ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
.executeProtobuf(CreateWsResponse.class);
ComponentDto project = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get();
@Test
public void do_not_add_project_to_user_favorites_if_project_creator_is_defined_in_permission_template_and_already_100_favorites() {
- OrganizationDto organization = db.organizations().insert();
UserDto user = db.users().insertUser();
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject(), user.getUuid()));
ws.newRequest()
.setParam("project", DEFAULT_PROJECT_KEY)
.setParam("name", DEFAULT_PROJECT_NAME)
- .setParam("organization", organization.getKey())
.executeProtobuf(CreateWsResponse.class);
ComponentDto project = db.getDbClient().componentDao().selectByKey(db.getSession(), DEFAULT_PROJECT_KEY).get();
@Test
public void fail_when_project_already_exists() {
- OrganizationDto organization = db.organizations().insert();
db.components().insertPublicProject(project -> project.setDbKey(DEFAULT_PROJECT_KEY));
userSession.addPermission(PROVISION_PROJECTS);
- expectedException.expect(BadRequestException.class);
-
- call(CreateRequest.builder()
- .setOrganization(organization.getKey())
+ CreateRequest request = CreateRequest.builder()
.setProjectKey(DEFAULT_PROJECT_KEY)
.setName(DEFAULT_PROJECT_NAME)
- .build());
+ .build();
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(BadRequestException.class);
}
@Test
public void fail_when_invalid_project_key() {
userSession.addPermission(PROVISION_PROJECTS);
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("Malformed key for Project: 'project%Key'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
-
- call(CreateRequest.builder()
+ CreateRequest request = CreateRequest.builder()
.setProjectKey("project%Key")
.setName(DEFAULT_PROJECT_NAME)
- .build());
+ .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);
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'project' parameter is missing");
-
- call(null, null, DEFAULT_PROJECT_NAME);
+ assertThatThrownBy(() -> call(null, DEFAULT_PROJECT_NAME))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The 'project' parameter is missing");
}
@Test
public void fail_when_missing_name_parameter() {
userSession.addPermission(PROVISION_PROJECTS);
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'name' parameter is missing");
-
- call(null, DEFAULT_PROJECT_KEY, null);
+ assertThatThrownBy(() -> call(DEFAULT_PROJECT_KEY, null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The 'name' parameter is missing");
}
@Test
public void fail_when_missing_create_project_permission() {
- expectedException.expect(ForbiddenException.class);
-
- call(CreateRequest.builder().setProjectKey(DEFAULT_PROJECT_KEY).setName(DEFAULT_PROJECT_NAME).build());
+ CreateRequest request = CreateRequest.builder().setProjectKey(DEFAULT_PROJECT_KEY).setName(DEFAULT_PROJECT_NAME)
+ .build();
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
assertThat(definition.params()).extracting(WebService.Param::key).containsExactlyInAnyOrder(
PARAM_VISIBILITY,
- PARAM_ORGANIZATION,
PARAM_NAME,
PARAM_PROJECT);
- WebService.Param organization = definition.param(PARAM_ORGANIZATION);
- assertThat(organization.description()).isEqualTo("The key of the organization");
- assertThat(organization.isInternal()).isTrue();
- assertThat(organization.isRequired()).isFalse();
- assertThat(organization.since()).isEqualTo("6.3");
-
WebService.Param visibilityParam = definition.param(PARAM_VISIBILITY);
assertThat(visibilityParam.description()).isNotEmpty();
assertThat(visibilityParam.isInternal()).isFalse();
@Test
public void fail_when_set_null_project_name_on_create_request_builder() {
- expectedException.expect(NullPointerException.class);
-
- CreateRequest.builder()
- .setProjectKey(DEFAULT_PROJECT_KEY)
- .setName(null);
+ 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() {
- expectedException.expect(NullPointerException.class);
-
- CreateRequest.builder()
- .setProjectKey(null)
+ 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() {
- expectedException.expect(NullPointerException.class);
CreateRequest.builder()
- .setName(DEFAULT_PROJECT_NAME)
- .build();
+ .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() {
- expectedException.expect(NullPointerException.class);
-
- CreateRequest.builder()
- .setProjectKey(DEFAULT_PROJECT_KEY)
- .build();
+ Builder builder = CreateRequest.builder()
+ .setProjectKey(DEFAULT_PROJECT_KEY);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
private CreateWsResponse call(CreateRequest request) {
- return call(request.getOrganization(), request.getProjectKey(), request.getName());
+ return call(request.getProjectKey(), request.getName());
}
- private CreateWsResponse call(@Nullable String organization, @Nullable String projectKey, @Nullable String projectName) {
+ private CreateWsResponse call(@Nullable String projectKey, @Nullable String projectName) {
TestRequest httpRequest = ws.newRequest()
.setMethod(POST.name());
- ofNullable(organization).ifPresent(org -> httpRequest.setParam("organization", org));
ofNullable(projectKey).ifPresent(key -> httpRequest.setParam("project", key));
ofNullable(projectName).ifPresent(name -> httpRequest.setParam("name", name));
return httpRequest.executeProtobuf(CreateWsResponse.class);
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.utils.System2;
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.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
public class DeleteActionTest {
- private System2 system2 = System2.INSTANCE;
+ private final System2 system2 = System2.INSTANCE;
@Rule
- public DbTester db = DbTester.create(system2);
+ public final DbTester db = DbTester.create(system2);
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSessionRule = UserSessionRule.standalone();
- private DbClient dbClient = db.getDbClient();
- private DbSession dbSession = db.getSession();
- private WebhookDbTester webhookDbTester = db.webhooks();
- private ComponentDbTester componentDbTester = new ComponentDbTester(db);
- private ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
- private ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class);
- private ResourceTypes mockResourceTypes = mock(ResourceTypes.class);
+ private final DbClient dbClient = db.getDbClient();
+ private final DbSession dbSession = db.getSession();
+ private final WebhookDbTester webhookDbTester = db.webhooks();
+ private final ComponentDbTester componentDbTester = new ComponentDbTester(db);
+ private final ComponentCleanerService componentCleanerService = mock(ComponentCleanerService.class);
+ private final ProjectLifeCycleListeners projectLifeCycleListeners = mock(ProjectLifeCycleListeners.class);
+ private final ResourceTypes mockResourceTypes = mock(ResourceTypes.class);
- private DeleteAction underTest = new DeleteAction(
+ private final DeleteAction underTest = new DeleteAction(
componentCleanerService,
from(db),
dbClient,
userSessionRule, projectLifeCycleListeners);
- private WsActionTester tester = new WsActionTester(underTest);
+ private final WsActionTester tester = new WsActionTester(underTest);
@Test
- public void organization_administrator_deletes_project_by_key() {
+ public void global_administrator_deletes_project_by_key() {
ComponentDto project = componentDbTester.insertPrivateProject();
userSessionRule.logIn().addPermission(ADMINISTER);
.addProjectPermission(UserRole.CODEVIEWER, project)
.addProjectPermission(UserRole.ISSUE_ADMIN, project)
.addProjectPermission(UserRole.USER, project);
- expectedException.expect(ForbiddenException.class);
- call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey()));
+ TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey());
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
ComponentDto project = componentDbTester.insertPrivateProject();
userSessionRule.anonymous();
- expectedException.expect(UnauthorizedException.class);
- call(tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey()));
+ TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, project.getDbKey());
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(UnauthorizedException.class);
}
@Test
userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage(String.format("Project '%s' not found", branch.getDbKey()));
-
- call(tester.newRequest().setParam(PARAM_PROJECT, branch.getDbKey()));
+ TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, branch.getDbKey());
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage(String.format("Project '%s' not found", branch.getDbKey()));
}
private String verifyDeletedKey() {
public void verify_count_of_added_components_on_SonarQube() {
ComponentContainer container = new ComponentContainer();
new ProjectsWsModule().configure(container);
- assertThat(container.size()).isEqualTo(COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER + 13);
+ assertThat(container.size()).isEqualTo(COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER + 12);
}
}
import java.util.Collections;
import java.util.Date;
import java.util.List;
-import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.organization.DefaultOrganizationProvider;
-import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
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.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.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_ORGANIZATION;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
private static final String PROJECT_KEY_3 = "project3";
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
+ public final DbTester db = DbTester.create();
- @Rule
- public DbTester db = DbTester.create();
-
- private final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
-
- private final WsActionTester ws = new WsActionTester(
- new SearchAction(db.getDbClient(), userSession, new ProjectsWsSupport(db.getDbClient(), defaultOrganizationProvider)));
+ 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().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("project-_%-key"),
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("PROJECT-_%-KEY"),
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("project-key-without-escaped-characters"));
+ ComponentTesting.newPrivateProjectDto().setDbKey("project-_%-key"),
+ ComponentTesting.newPrivateProjectDto().setDbKey("PROJECT-_%-KEY"),
+ ComponentTesting.newPrivateProjectDto().setDbKey("project-key-without-escaped-characters"));
SearchWsResponse response = call(SearchRequest.builder().setQuery("JeCt-_%-k").build());
public void search_private_projects() {
userSession.addPermission(ADMINISTER);
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("private-key"),
- ComponentTesting.newPublicProjectDto(db.getDefaultOrganization()).setDbKey("public-key"));
+ ComponentTesting.newPrivateProjectDto().setDbKey("private-key"),
+ ComponentTesting.newPublicProjectDto().setDbKey("public-key"));
SearchWsResponse response = call(SearchRequest.builder().setVisibility("private").build());
public void search_public_projects() {
userSession.addPermission(ADMINISTER);
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("private-key"),
- ComponentTesting.newPublicProjectDto(db.getDefaultOrganization()).setDbKey("public-key"));
+ ComponentTesting.newPrivateProjectDto().setDbKey("private-key"),
+ ComponentTesting.newPublicProjectDto().setDbKey("public-key"));
SearchWsResponse response = call(SearchRequest.builder().setVisibility("public").build());
public void search_projects_when_no_qualifier_set() {
userSession.addPermission(ADMINISTER);
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_1),
- newView(db.getDefaultOrganization()));
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_1),
+ newView());
SearchWsResponse response = call(SearchRequest.builder().build());
@Test
public void search_projects() {
userSession.addPermission(ADMINISTER);
- ComponentDto project = ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_1);
+ ComponentDto project = ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_1);
ComponentDto module = newModuleDto(project);
ComponentDto directory = newDirectory(module, "dir");
ComponentDto file = newFileDto(directory);
db.components().insertComponents(
project, module, directory, file,
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_2),
- newView(db.getDefaultOrganization()));
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_2),
+ newView());
SearchWsResponse response = call(SearchRequest.builder().setQualifiers(singletonList("TRK")).build());
public void search_views() {
userSession.addPermission(ADMINISTER);
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_1),
- newView(db.getDefaultOrganization()).setDbKey("view1"));
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_1),
+ newView().setDbKey("view1"));
SearchWsResponse response = call(SearchRequest.builder().setQualifiers(singletonList("VW")).build());
public void search_projects_and_views() {
userSession.addPermission(ADMINISTER);
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_1),
- newView(db.getDefaultOrganization()).setDbKey("view1"));
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_1),
+ newView().setDbKey("view1"));
SearchWsResponse response = call(SearchRequest.builder().setQualifiers(asList("TRK", "VW")).build());
}
@Test
- public void search_on_default_organization_when_no_organization_set() {
+ public void search_all() {
userSession.addPermission(ADMINISTER);
- OrganizationDto otherOrganization = db.organizations().insert();
db.components().insertComponents(
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_1),
- ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey(PROJECT_KEY_2),
- ComponentTesting.newPrivateProjectDto(otherOrganization).setDbKey(PROJECT_KEY_3));
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_1),
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_2),
+ ComponentTesting.newPrivateProjectDto().setDbKey(PROJECT_KEY_3));
SearchWsResponse response = call(SearchRequest.builder().build());
- assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1, PROJECT_KEY_2);
- }
-
- @Test
- public void search_for_projects_on_given_organization() {
- OrganizationDto organization1 = db.organizations().insert();
- OrganizationDto organization2 = db.organizations().insert();
- userSession.addPermission(ADMINISTER);
- ComponentDto project1 = ComponentTesting.newPrivateProjectDto(organization1);
- ComponentDto project2 = ComponentTesting.newPrivateProjectDto(organization1);
- ComponentDto project3 = ComponentTesting.newPrivateProjectDto(organization2);
- db.components().insertComponents(project1, project2, project3);
-
- SearchWsResponse response = call(SearchRequest.builder().setOrganization(organization1.getKey()).build());
-
- assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(project1.getDbKey(), project2.getDbKey());
+ assertThat(response.getComponentsList()).extracting(Component::getKey).containsOnly(PROJECT_KEY_1, PROJECT_KEY_2, PROJECT_KEY_3);
}
@Test
userSession.addPermission(ADMINISTER);
List<ComponentDto> componentDtoList = new ArrayList<>();
for (int i = 1; i <= 9; i++) {
- componentDtoList.add(newPrivateProjectDto(db.getDefaultOrganization(), "project-uuid-" + i).setDbKey("project-key-" + i).setName("Project Name " + i));
+ componentDtoList.add(newPrivateProjectDto("project-uuid-" + i).setDbKey("project-key-" + i).setName("Project Name " + i));
}
db.components().insertComponents(componentDtoList.toArray(new ComponentDto[] {}));
@Test
public void request_throws_IAE_if_more_than_1000_projects() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("'projects' can contains only 1000 values, got 1001");
-
- call(SearchRequest.builder()
+ SearchRequest request = SearchRequest.builder()
.setProjects(Collections.nCopies(1_001, "foo"))
- .build());
+ .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);
- expectedException.expect(ForbiddenException.class);
-
- call(SearchRequest.builder().build());
- }
-
- @Test
- public void fail_on_unknown_organization() {
- expectedException.expect(NotFoundException.class);
- call(SearchRequest.builder().setOrganization("unknown").build());
+ SearchRequest request = SearchRequest.builder().build();
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_on_invalid_qualifier() {
userSession.addPermission(ADMINISTER_QUALITY_PROFILES);
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Value of parameter 'qualifiers' (BRC) must be one of: [TRK, VW, APP]");
- call(SearchRequest.builder().setQualifiers(singletonList("BRC")).build());
+ 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
assertThat(action.since()).isEqualTo("6.3");
assertThat(action.handler()).isEqualTo(ws.getDef().handler());
assertThat(action.params()).extracting(Param::key)
- .containsExactlyInAnyOrder("organization", "q", "qualifiers", "p", "ps", "visibility", "analyzedBefore", "onProvisionedOnly", "projects");
+ .containsExactlyInAnyOrder("q", "qualifiers", "p", "ps", "visibility", "analyzedBefore", "onProvisionedOnly", "projects");
assertThat(action.responseExample()).isEqualTo(getClass().getResource("search-example.json"));
- Param organization = action.param("organization");
- Assertions.assertThat(organization.description()).isEqualTo("The key of the organization");
- Assertions.assertThat(organization.isInternal()).isTrue();
- Assertions.assertThat(organization.isRequired()).isFalse();
- Assertions.assertThat(organization.since()).isEqualTo("6.3");
-
Param qParam = action.param("q");
assertThat(qParam.isRequired()).isFalse();
assertThat(qParam.description()).isEqualTo("Limit search to: " +
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 of the organization will be used.");
+ "If no visibility is specified, the default project visibility will be used.");
Param lastAnalysisBefore = action.param("analyzedBefore");
assertThat(lastAnalysisBefore.isRequired()).isFalse();
@Test
public void json_example() {
- OrganizationDto organization = db.organizations().insertForKey("my-org-1");
userSession.addPermission(ADMINISTER);
- ComponentDto publicProject = newPrivateProjectDto(organization, "project-uuid-1").setName("Project Name 1").setDbKey("project-key-1").setPrivate(false);
- ComponentDto privateProject = newPrivateProjectDto(organization, "project-uuid-2").setName("Project Name 1").setDbKey("project-key-2");
+ ComponentDto publicProject = newPrivateProjectDto("project-uuid-1").setName("Project Name 1").setDbKey("project-key-1").setPrivate(false);
+ ComponentDto privateProject = newPrivateProjectDto("project-uuid-2").setName("Project Name 1").setDbKey("project-key-2");
db.components().insertComponents(
publicProject,
privateProject);
String response = ws.newRequest()
.setMediaType(MediaTypes.JSON)
- .setParam(PARAM_ORGANIZATION, organization.getKey())
.execute().getInput();
assertJson(response).isSimilarTo(ws.getDef().responseExampleAsString());
private SearchWsResponse call(SearchRequest wsRequest) {
TestRequest request = ws.newRequest();
- ofNullable(wsRequest.getOrganization()).ifPresent(organization -> request.setParam(PARAM_ORGANIZATION, organization));
List<String> qualifiers = wsRequest.getQualifiers();
if (!qualifiers.isEmpty()) {
request.setParam(ComponentsWsParameters.PARAM_QUALIFIERS, Joiner.on(",").join(qualifiers));
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
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.db.component.ProjectLinkDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.metric.MetricDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.UnauthorizedException;
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.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.ComponentTesting.newView;
public class SearchMyProjectsActionTest {
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
+ public final DbTester db = DbTester.create(System2.INSTANCE);
- private DbClient dbClient = db.getDbClient();
- private DbSession dbSession = db.getSession();
+ private final DbClient dbClient = db.getDbClient();
+ private final DbSession dbSession = db.getSession();
private WsActionTester ws;
private UserDto user;
private MetricDto alertStatusMetric;
@Test
public void search_json_example() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(organizationDto);
- ComponentDto cLang = insertClang(organizationDto);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto cLang = insertClang();
db.componentLinks().insertProvidedLink(jdk7, l -> l.setHref("http://www.oracle.com").setType(ProjectLinkDto.TYPE_HOME_PAGE).setName("Home"));
db.componentLinks().insertProvidedLink(jdk7, 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();
@Test
public void return_only_current_user_projects() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(organizationDto);
- ComponentDto cLang = insertClang(organizationDto);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto cLang = insertClang();
UserDto anotherUser = db.users().insertUser(newUserDto());
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7);
db.users().insertProjectPermissionOnUser(anotherUser, UserRole.ADMIN, cLang);
@Test
public void return_only_first_1000_projects() {
- OrganizationDto organization = db.organizations().insert();
IntStream.range(0, 1_010).forEach(i -> {
- ComponentDto project = db.components().insertComponent(newPrivateProjectDto(organization));
+ ComponentDto project = db.components().insertComponent(newPrivateProjectDto());
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project);
});
@Test
public void sort_projects_by_name() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto b_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setName("B_project_name"));
- ComponentDto c_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setName("c_project_name"));
- ComponentDto a_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setName("A_project_name"));
+ ComponentDto b_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setName("B_project_name"));
+ ComponentDto c_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setName("c_project_name"));
+ ComponentDto a_project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setName("A_project_name"));
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, b_project);
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, a_project);
@Test
public void paginate_projects() {
- OrganizationDto organizationDto = db.organizations().insert();
for (int i = 0; i < 10; i++) {
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setName("project-" + i));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setName("project-" + i));
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, project);
}
@Test
public void return_only_projects_when_user_is_admin() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(organizationDto);
- ComponentDto clang = insertClang(organizationDto);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto clang = insertClang();
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7);
db.users().insertProjectPermissionOnUser(user, UserRole.ISSUE_ADMIN, clang);
@Test
public void does_not_return_views() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(organizationDto);
- ComponentDto view = insertView(organizationDto);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto view = insertView();
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, jdk7);
db.users().insertProjectPermissionOnUser(user, UserRole.ADMIN, view);
@Test
public void admin_via_groups() {
- OrganizationDto org = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(org);
- ComponentDto cLang = insertClang(org);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto cLang = insertClang();
GroupDto group = db.users().insertGroup();
db.users().insertMember(group, user);
@Test
public void admin_via_groups_and_users() {
- OrganizationDto org = db.organizations().insert();
- ComponentDto jdk7 = insertJdk7(org);
- ComponentDto cLang = insertClang(org);
- ComponentDto sonarqube = db.components().insertPrivateProject(org);
+ ComponentDto jdk7 = insertJdk7();
+ ComponentDto cLang = insertClang();
+ ComponentDto sonarqube = db.components().insertPrivateProject();
GroupDto group = db.users().insertGroup();
db.users().insertMember(group, user);
@Test
public void fail_if_not_authenticated() {
userSession.anonymous();
- expectedException.expect(UnauthorizedException.class);
- callWs();
+ assertThatThrownBy(this::callWs)
+ .isInstanceOf(UnauthorizedException.class);
}
- private ComponentDto insertClang(OrganizationDto organizationDto) {
- return db.components().insertComponent(newPrivateProjectDto(organizationDto, Uuids.UUID_EXAMPLE_01)
+ private ComponentDto insertClang() {
+ return db.components().insertComponent(newPrivateProjectDto(Uuids.UUID_EXAMPLE_01)
.setName("Clang")
.setDbKey("clang"));
}
- private ComponentDto insertJdk7(OrganizationDto organizationDto) {
- return db.components().insertComponent(newPrivateProjectDto(organizationDto, Uuids.UUID_EXAMPLE_02)
+ private ComponentDto insertJdk7() {
+ return db.components().insertComponent(newPrivateProjectDto(Uuids.UUID_EXAMPLE_02)
.setName("JDK 7")
.setDbKey("net.java.openjdk:jdk7")
.setDescription("JDK"));
}
- private ComponentDto insertView(OrganizationDto organizationDto) {
- return db.components().insertComponent(newView(organizationDto, "752d8bfd-420c-4a83-a4e5-8ab19b13c8fc")
+ private ComponentDto insertView() {
+ return db.components().insertComponent(newView("752d8bfd-420c-4a83-a4e5-8ab19b13c8fc")
.setName("Java")
.setDbKey("Java"));
}
*/
package org.sonar.server.project.ws;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.sonar.server.project.ws.SearchMyProjectsData.Builder;
import static java.util.Collections.emptyList;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SearchMyProjectsDataTest {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- SearchMyProjectsData.Builder underTest = SearchMyProjectsData.builder();
+ private final SearchMyProjectsData.Builder underTest = SearchMyProjectsData.builder();
@Test
public void fail_if_projects_are_not_provided() {
- expectedException.expect(NullPointerException.class);
-
- underTest
+ Builder builder = underTest
.setProjects(null)
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
.setQualityGates(emptyList())
- .setTotalNbOfProjects(0)
- .build();
+ .setTotalNbOfProjects(0);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_projects_links_are_not_provided() {
- expectedException.expect(NullPointerException.class);
-
- underTest
+ Builder builder = underTest
.setProjects(emptyList())
.setProjectLinks(null)
.setSnapshots(emptyList())
.setQualityGates(emptyList())
- .setTotalNbOfProjects(0)
- .build();
+ .setTotalNbOfProjects(0);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_snapshots_are_not_provided() {
- expectedException.expect(NullPointerException.class);
-
- underTest
+ Builder builder = underTest
.setProjects(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(null)
.setQualityGates(emptyList())
- .setTotalNbOfProjects(0)
- .build();
+ .setTotalNbOfProjects(0);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_quality_gates_are_not_provided() {
- expectedException.expect(NullPointerException.class);
-
- underTest
+ Builder builder = underTest
.setProjects(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
- .setQualityGates(null)
- .build();
+ .setQualityGates(null);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
@Test
public void fail_if_total_number_of_projects_is_not_provided() {
- expectedException.expect(NullPointerException.class);
-
- underTest
+ Builder builder = underTest
.setProjects(emptyList())
.setProjectLinks(emptyList())
.setSnapshots(emptyList())
.setQualityGates(emptyList())
- .setTotalNbOfProjects(null)
- .build();
+ .setTotalNbOfProjects(null);
+ assertThatThrownBy(builder::build)
+ .isInstanceOf(NullPointerException.class);
}
}
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
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;
private static final String ANOTHER_KEY = "another_key";
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final DbTester db = DbTester.create(System2.INSTANCE);
@Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
- @Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone();
- private DbClient dbClient = db.getDbClient();
- private ProjectIndexers projectIndexers = new ProjectIndexersImpl();
- private ComponentService componentService = new ComponentService(dbClient, userSessionRule, projectIndexers, new ProjectLifeCycleListenersImpl());
- private ComponentFinder componentFinder = new ComponentFinder(dbClient, null);
- private WsActionTester ws = new WsActionTester(new UpdateKeyAction(dbClient, componentService, componentFinder));
+ public final UserSessionRule userSessionRule = UserSessionRule.standalone();
+ private final DbClient dbClient = db.getDbClient();
+ private final ProjectIndexers projectIndexers = new ProjectIndexersImpl();
+ private final ComponentService componentService = new ComponentService(dbClient, userSessionRule, projectIndexers, 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() {
ComponentDto project = insertProject();
userSessionRule.addProjectPermission(UserRole.USER, project);
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- call(project.getKey(), ANOTHER_KEY);
+ String projectKey = project.getKey();
+ assertThatThrownBy(() -> call(projectKey, ANOTHER_KEY))
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
@Test
ComponentDto project = insertProject();
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'to' parameter is missing");
-
- call(project.getKey(), null);
+ String projectKey = project.getKey();
+ assertThatThrownBy(() -> call(projectKey, null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The 'to' parameter is missing");
}
@Test
public void fail_if_key_not_provided() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'from' parameter is missing");
-
- call(null, ANOTHER_KEY);
+ assertThatThrownBy(() -> call(null, ANOTHER_KEY))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The 'from' parameter is missing");
}
@Test
public void fail_if_project_does_not_exist() {
- expectedException.expect(NotFoundException.class);
-
- call("UNKNOWN_UUID", ANOTHER_KEY);
+ assertThatThrownBy(() -> call("UNKNOWN_UUID", ANOTHER_KEY))
+ .isInstanceOf(NotFoundException.class);
}
@Test
ComponentDto branch = db.components().insertProjectBranch(project);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage(String.format("Project '%s' not found", branch.getDbKey()));
-
- call(branch.getDbKey(), ANOTHER_KEY);
+ String branchDbKey = branch.getDbKey();
+ assertThatThrownBy(() -> call(branchDbKey, ANOTHER_KEY))
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage(String.format("Project '%s' not found", branchDbKey));
}
@Test
}
private ComponentDto insertProject() {
- return db.components().insertPrivateProject(db.organizations().insert());
+ return db.components().insertPrivateProject();
}
private String call(@Nullable String key, @Nullable String newKey) {
import java.util.stream.Stream;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ResourceTypesRule;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.permission.GroupPermissionDto;
import org.sonar.db.permission.UserPermissionDto;
import static java.lang.String.format;
import static java.util.Arrays.stream;
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.component.ComponentTesting.newProjectCopy;
private static final String PUBLIC = "public";
private static final String PRIVATE = "private";
- private static final Set<String> ORGANIZATION_PERMISSIONS_NAME_SET = stream(GlobalPermission.values()).map(GlobalPermission::getKey)
+ private static final Set<String> GLOBAL_PERMISSIONS_NAME_SET = stream(GlobalPermission.values()).map(GlobalPermission::getKey)
.collect(MoreCollectors.toSet(GlobalPermission.values().length));
@Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
+ public final DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
- public EsTester es = EsTester.createCustom(new FooIndexDefinition());
+ public final EsTester es = EsTester.createCustom(new FooIndexDefinition());
@Rule
- public UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSessionRule = UserSessionRule.standalone().logIn();
private final ResourceTypes resourceTypes = new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT);
private final PermissionService permissionService = new PermissionServiceImpl(resourceTypes);
public void execute_fails_if_user_is_not_logged_in() {
userSessionRule.anonymous();
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- request.execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(UnauthorizedException.class)
+ .hasMessage("Authentication is required");
}
@Test
public void execute_fails_with_IAE_when_project_parameter_is_not_provided() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'project' parameter is missing");
-
- request.execute();
+ 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() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'project' parameter is missing");
-
- request.execute();
+ 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");
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("The 'visibility' parameter is missing");
-
- request.execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("The 'visibility' parameter is missing");
}
@Test
request.setParam(PARAM_PROJECT, "foo")
.setParam(PARAM_VISIBILITY, "");
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Value of parameter '" + PARAM_VISIBILITY + "' () must be one of: [private, public]");
-
- request.execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Value of parameter '" + PARAM_VISIBILITY + "' () must be one of: [private, public]");
}
@Test
request.setParam(PARAM_PROJECT, "foo")
.setParam(PARAM_VISIBILITY, randomVisibility);
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage("Component key 'foo' not found");
-
- request.execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Component key 'foo' not found");
}
@Test
public void execute_fails_with_BadRequestException_if_specified_component_is_neither_a_project_a_portfolio_nor_an_application() {
- OrganizationDto organization = dbTester.organizations().insert();
ComponentDto project = randomPublicOrPrivateProject();
ComponentDto module = ComponentTesting.newModuleDto(project);
ComponentDto dir = ComponentTesting.newDirectory(project, "path");
ComponentDto file = ComponentTesting.newFileDto(project);
dbTester.components().insertComponents(module, dir, file);
- ComponentDto application = dbTester.components().insertPublicApplication(organization);
- ComponentDto portfolio = dbTester.components().insertView(organization);
+ ComponentDto application = dbTester.components().insertPublicApplication();
+ ComponentDto portfolio = dbTester.components().insertView();
ComponentDto subView = ComponentTesting.newSubView(portfolio);
ComponentDto projectCopy = newProjectCopy("foo", project, subView);
dbTester.components().insertComponents(subView, projectCopy);
@Test
public void execute_throws_ForbiddenException_if_user_has_no_permission_on_specified_component() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPrivateProject(organization);
+ ComponentDto project = dbTester.components().insertPrivateProject();
request.setParam(PARAM_PROJECT, project.getDbKey())
.setParam(PARAM_VISIBILITY, randomVisibility);
- expectInsufficientPrivilegeException();
-
- request.execute();
+ 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() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPublicProject(organization);
+ ComponentDto project = dbTester.components().insertPublicProject();
request.setParam(PARAM_PROJECT, project.getDbKey())
.setParam(PARAM_VISIBILITY, randomVisibility);
userSessionRule.addProjectPermission(UserRole.ISSUE_ADMIN, project);
request.setParam(PARAM_PROJECT, project.getDbKey())
.setParam(PARAM_VISIBILITY, randomVisibility);
- expectInsufficientPrivilegeException();
-
- request.execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
@Test
.setParam(PARAM_VISIBILITY, randomVisibility);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("Component visibility can't be changed as long as it has background task(s) pending or in progress");
-
- request.execute();
+ 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
.setParam(PARAM_VISIBILITY, randomVisibility);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("Component visibility can't be changed as long as it has background task(s) pending or in progress");
-
- request.execute();
+ 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
@Test
public void execute_deletes_all_permissions_to_Anyone_on_specified_project_when_new_visibility_is_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPublicProject(organization);
+ ComponentDto project = dbTester.components().insertPublicProject();
UserDto user = dbTester.users().insertUser();
GroupDto group = dbTester.users().insertGroup();
- unsafeGiveAllPermissionsToRootComponent(project, user, group, organization);
+ unsafeGiveAllPermissionsToRootComponent(project, user, group);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
request.setParam(PARAM_PROJECT, project.getDbKey())
@Test
public void execute_does_not_delete_all_permissions_to_AnyOne_on_specified_project_if_already_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPrivateProject(organization);
+ ComponentDto project = dbTester.components().insertPrivateProject();
UserDto user = dbTester.users().insertUser();
GroupDto group = dbTester.users().insertGroup();
- unsafeGiveAllPermissionsToRootComponent(project, user, group, organization);
+ unsafeGiveAllPermissionsToRootComponent(project, user, group);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
request.setParam(PARAM_PROJECT, project.getDbKey())
@Test
public void execute_deletes_all_permissions_USER_and_BROWSE_of_specified_project_when_new_visibility_is_public() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPrivateProject(organization);
+ ComponentDto project = dbTester.components().insertPrivateProject();
UserDto user = dbTester.users().insertUser();
GroupDto group = dbTester.users().insertGroup();
- unsafeGiveAllPermissionsToRootComponent(project, user, group, organization);
+ unsafeGiveAllPermissionsToRootComponent(project, user, group);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
request.setParam(PARAM_PROJECT, project.getDbKey())
@Test
public void execute_does_not_delete_permissions_USER_and_BROWSE_of_specified_project_when_new_component_is_already_public() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPublicProject(organization);
+ ComponentDto project = dbTester.components().insertPublicProject();
UserDto user = dbTester.users().insertUser();
GroupDto group = dbTester.users().insertGroup();
- unsafeGiveAllPermissionsToRootComponent(project, user, group, organization);
+ unsafeGiveAllPermissionsToRootComponent(project, user, group);
userSessionRule.addProjectPermission(UserRole.ADMIN, project);
request.setParam(PARAM_PROJECT, project.getDbKey())
@Test
public void execute_grants_USER_and_CODEVIEWER_permissions_to_any_user_with_at_least_one_permission_when_making_project_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPublicProject(organization);
+ ComponentDto project = dbTester.components().insertPublicProject();
UserDto user1 = dbTester.users().insertUser();
UserDto user2 = dbTester.users().insertUser();
UserDto user3 = dbTester.users().insertUser();
@Test
public void execute_grants_USER_and_CODEVIEWER_permissions_to_any_group_with_at_least_one_permission_when_making_project_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto project = dbTester.components().insertPublicProject(organization);
+ ComponentDto project = dbTester.components().insertPublicProject();
GroupDto group1 = dbTester.users().insertGroup();
GroupDto group2 = dbTester.users().insertGroup();
GroupDto group3 = dbTester.users().insertGroup();
@Test
public void update_a_portfolio_to_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto portfolio = dbTester.components().insertPublicPortfolio(organization);
+ ComponentDto portfolio = dbTester.components().insertPublicPortfolio();
GroupDto group = dbTester.users().insertGroup();
dbTester.users().insertProjectPermissionOnGroup(group, UserRole.ISSUE_ADMIN, portfolio);
UserDto user = dbTester.users().insertUser();
@Test
public void update_a_portfolio_to_public() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto portfolio = dbTester.components().insertPrivatePortfolio(organization);
+ ComponentDto portfolio = dbTester.components().insertPrivatePortfolio();
userSessionRule.addProjectPermission(UserRole.ADMIN, portfolio);
GroupDto group = dbTester.users().insertGroup();
dbTester.users().insertProjectPermissionOnGroup(group, UserRole.ISSUE_ADMIN, portfolio);
@Test
public void update_an_application_to_private() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto application = dbTester.components().insertPublicApplication(organization);
+ ComponentDto application = dbTester.components().insertPublicApplication();
GroupDto group = dbTester.users().insertGroup();
dbTester.users().insertProjectPermissionOnGroup(group, UserRole.ISSUE_ADMIN, application);
UserDto user = dbTester.users().insertUser();
@Test
public void update_an_application_to_public() {
- OrganizationDto organization = dbTester.organizations().insert();
- ComponentDto portfolio = dbTester.components().insertPrivateApplication(organization);
+ ComponentDto portfolio = dbTester.components().insertPrivateApplication();
userSessionRule.addProjectPermission(UserRole.ADMIN, portfolio);
GroupDto group = dbTester.users().insertGroup();
dbTester.users().insertProjectPermissionOnGroup(group, UserRole.ISSUE_ADMIN, portfolio);
userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = dbTester.components().insertProjectBranch(project);
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage(String.format("Component key '%s' not found", branch.getDbKey()));
-
- request.setParam(PARAM_PROJECT, branch.getDbKey())
- .setParam(PARAM_VISIBILITY, PUBLIC)
- .execute();
+ TestRequest request = this.request.setParam(PARAM_PROJECT, branch.getDbKey())
+ .setParam(PARAM_VISIBILITY, PUBLIC);
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage(String.format("Component key '%s' not found", branch.getDbKey()));
}
- private void unsafeGiveAllPermissionsToRootComponent(ComponentDto component, UserDto user, GroupDto group, OrganizationDto organization) {
+ private void unsafeGiveAllPermissionsToRootComponent(ComponentDto component, UserDto user, GroupDto group) {
Arrays.stream(GlobalPermission.values())
- .forEach(organizationPermission -> {
- dbTester.users().insertPermissionOnAnyone(organizationPermission);
- dbTester.users().insertPermissionOnGroup(group, organizationPermission);
- dbTester.users().insertPermissionOnUser(user, organizationPermission);
+ .forEach(globalPermission -> {
+ dbTester.users().insertPermissionOnAnyone(globalPermission);
+ dbTester.users().insertPermissionOnGroup(group, globalPermission);
+ dbTester.users().insertPermissionOnUser(user, globalPermission);
});
permissionService.getAllProjectPermissions()
.forEach(permission -> {
private void verifyHasAllPermissionsButProjectPermissionsToGroupAnyOne(ComponentDto component, UserDto user, GroupDto group) {
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectProjectPermissionsOfGroup(dbSession, null, component.uuid()))
.isEmpty();
assertThat(dbClient.groupPermissionDao().selectProjectPermissionsOfGroup(dbSession, group.getUuid(), component.uuid()))
private void verifyHasAllPermissionsButProjectPermissionsUserAndBrowse(ComponentDto component, UserDto user, GroupDto group) {
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectProjectPermissionsOfGroup(dbSession, null, component.uuid()))
.doesNotContain(UserRole.USER)
.doesNotContain(UserRole.CODEVIEWER)
private void verifyStillHasAllPermissions(ComponentDto component, UserDto user, GroupDto group) {
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, group.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.userPermissionDao().selectGlobalPermissionsOfUser(dbSession, user.getUuid()))
- .containsAll(ORGANIZATION_PERMISSIONS_NAME_SET);
+ .containsAll(GLOBAL_PERMISSIONS_NAME_SET);
assertThat(dbClient.groupPermissionDao().selectProjectPermissionsOfGroup(dbSession, null, component.uuid()))
.containsAll(permissionService.getAllProjectPermissions());
assertThat(dbClient.groupPermissionDao().selectProjectPermissionsOfGroup(dbSession, group.getUuid(), component.uuid()))
dbTester.commit();
}
- private void expectInsufficientPrivilegeException() {
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
- }
-
private boolean isPrivateInDb(ComponentDto project) {
return dbClient.componentDao().selectByUuid(dbTester.getSession(), project.uuid()).get().isPrivate();
}
private ComponentDto randomPublicOrPrivateProject() {
- OrganizationDto organization = dbTester.organizations().insert();
- return random.nextBoolean() ? dbTester.components().insertPublicProject(organization) : dbTester.components().insertPrivateProject(organization);
+ return random.nextBoolean() ? dbTester.components().insertPublicProject() : dbTester.components().insertPrivateProject();
}
}
@Test
public void throw_ForbiddenException_if_not_project_administrator() {
- SnapshotDto analysis = db.components().insertProjectAndSnapshot(newPrivateProjectDto(db.organizations().insert(), "P1"));
+ SnapshotDto analysis = db.components().insertProjectAndSnapshot(newPrivateProjectDto("P1"));
userSession.logIn();
expectedException.expect(ForbiddenException.class);
@Test
public void delete_event() {
- ComponentDto project = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+ ComponentDto project = ComponentTesting.newPrivateProjectDto();
SnapshotDto analysis = db.components().insertProjectAndSnapshot(project);
db.events().insertEvent(newEvent(analysis).setUuid("E1"));
db.events().insertEvent(newEvent(analysis).setUuid("E2"));
@Test
public void fail_if_category_different_than_other_and_version() {
- ComponentDto project = newPrivateProjectDto(db.organizations().insert(), "P1");
+ ComponentDto project = newPrivateProjectDto("P1");
SnapshotDto analysis = db.components().insertProjectAndSnapshot(project);
db.events().insertEvent(newEvent(analysis).setUuid("E1").setCategory("Profile"));
logInAsProjectAdministrator(project);
@Test
public void fail_if_not_enough_permission() {
- SnapshotDto analysis = db.components().insertProjectAndSnapshot(ComponentTesting.newPrivateProjectDto(db.organizations().insert()));
+ SnapshotDto analysis = db.components().insertProjectAndSnapshot(ComponentTesting.newPrivateProjectDto());
db.events().insertEvent(newEvent(analysis).setUuid("E1"));
userSession.logIn();
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.event.EventDto;
import org.sonar.db.event.EventTesting;
-import org.sonar.db.organization.OrganizationTesting;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
import static org.sonar.server.projectanalysis.ws.EventCategory.QUALITY_GATE;
}
private EventDto newEvent() {
- return EventTesting.newEvent(newAnalysis(ComponentTesting.newPrivateProjectDto(OrganizationTesting.newOrganizationDto())));
+ return EventTesting.newEvent(newAnalysis(ComponentTesting.newPrivateProjectDto()));
}
}
import org.sonar.db.event.EventPurgeData;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
@Test
public void json_example() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setDbKey(KEY_PROJECT_EXAMPLE_001));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setDbKey(KEY_PROJECT_EXAMPLE_001));
userSession.addProjectPermission(UserRole.USER, project);
SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(project)
.setCreatedAt(parseDateTime("2016-12-11T17:12:45+0100").getTime())
.setProjectVersion("1.2")
.setBuildString("1.2.0.322")
- .setRevision("bfe36592eb7f9f2708b5d358b5b5f33ed535c8cf")
- );
+ .setRevision("bfe36592eb7f9f2708b5d358b5b5f33ed535c8cf"));
SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(project)
.setUuid("A2")
.setCreatedAt(parseDateTime("2016-12-12T17:12:45+0100").getTime())
.setProjectVersion("1.2.1")
.setBuildString("1.2.1.423")
- .setRevision("be6c75b85da526349c44e3978374c95e0b80a96d")
- );
+ .setRevision("be6c75b85da526349c44e3978374c95e0b80a96d"));
SnapshotDto a3 = db.components().insertSnapshot(newAnalysis(project)
.setUuid("P1")
.setCreatedAt(parseDateTime("2015-11-11T10:00:00+0100").getTime())
@Test
public void return_only_processed_analyses() {
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization()).setDbKey("P1"));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setDbKey("P1"));
userSession.addProjectPermission(UserRole.USER, project);
db.components().insertSnapshot(newAnalysis(project).setUuid("A1"));
db.components().insertSnapshot(newAnalysis(project).setUuid("A2").setStatus(SnapshotDto.STATUS_UNPROCESSED));
@Test
public void return_events() {
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(organizationDto).setDbKey("P1"));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setDbKey("P1"));
userSession.addProjectPermission(UserRole.USER, project);
SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(project).setUuid("A1"));
- SnapshotDto a42 = db.components().insertSnapshot(newAnalysis(ComponentTesting.newPrivateProjectDto(organizationDto)).setUuid("A42"));
+ 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));
@Test
public void return_analyses_of_application() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
SnapshotDto secondAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(2_000_000L));
@Test
public void return_definition_change_events_on_application_analyses() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel()));
@Test
@UseDataProvider("changedBranches")
public void application_definition_change_with_branch(@Nullable String oldBranch, @Nullable String newBranch) {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel()));
@Test
public void incorrect_eventcomponentchange_two_identical_changes_added_on_same_project() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel()));
@Test
public void incorrect_eventcomponentchange_incorrect_category() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel()));
@Test
public void incorrect_eventcomponentchange_three_component_changes_on_same_project() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(newEvent(firstAnalysis).setName("").setUuid("E11").setCategory(DEFINITION_CHANGE.getLabel()));
@Test
public void incorrect_quality_gate_information() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto application = db.components().insertPublicApplication(organization);
+ ComponentDto application = db.components().insertPublicApplication();
userSession.registerComponents(application);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(application).setCreatedAt(1_000_000L));
EventDto event = db.events().insertEvent(
@Test
public void return_analyses_of_portfolio() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto view = db.components().insertView(organization);
+ ComponentDto view = db.components().insertView();
userSession.registerComponents(view);
SnapshotDto firstAnalysis = db.components().insertSnapshot(newAnalysis(view).setCreatedAt(1_000_000L));
SnapshotDto secondAnalysis = db.components().insertSnapshot(newAnalysis(view).setCreatedAt(2_000_000L));
@Test
public void filter_by_category() {
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(db.organizations().insert()).setDbKey("P1"));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setDbKey("P1"));
userSession.addProjectPermission(UserRole.USER, project);
SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(project).setUuid("A1"));
SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(project).setUuid("A2"));
@Test
public void paginate_with_filter_on_category() {
- ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto(db.organizations().insert()).setDbKey("P1"));
+ ComponentDto project = db.components().insertComponent(ComponentTesting.newPrivateProjectDto().setDbKey("P1"));
userSession.addProjectPermission(UserRole.USER, project);
SnapshotDto a1 = db.components().insertSnapshot(newAnalysis(project).setUuid("A1").setCreatedAt(1_000_000L));
SnapshotDto a2 = db.components().insertSnapshot(newAnalysis(project).setUuid("A2").setCreatedAt(2_000_000L));
.setProject(project.getKey())
.setBranch("my_branch")
.build())
- .getAnalysesList();
+ .getAnalysesList();
assertThat(result).extracting(Analysis::getKey).containsExactlyInAnyOrder(analysis.getUuid());
assertThat(result.get(0).getEventsList()).extracting(Event::getKey).containsExactlyInAnyOrder(event.getUuid());
tuple(analyses[0].getUuid(), "", ""),
tuple(analyses[1].getUuid(), "a", ""),
tuple(analyses[2].getUuid(), "", "b"),
- tuple(analyses[3].getUuid(), "c", "d")
- );
+ tuple(analyses[3].getUuid(), "c", "d"));
}
@Test
SnapshotDto analysis = db.components().insertSnapshot(project);
logInAsProjectAdministrator(project);
- ComponentDto otherProject = tester.insertPrivateProjectWithCustomBranch(db.getDefaultOrganization(), branch -> branch.setKey("main"));
+ ComponentDto otherProject = tester.insertPrivateProjectWithCustomBranch("main");
BranchDto branchOfOtherProject = branchDao.selectByUuid(dbSession, otherProject.uuid()).get();
expectedException.expect(NotFoundException.class);
@Test
public void fail_when_analysis_does_not_belong_to_main_branch_of_project() {
- ComponentDto project = tester.insertPrivateProjectWithCustomBranch(db.getDefaultOrganization(), b -> b.setKey("branch1"));
+ ComponentDto project = tester.insertPrivateProjectWithCustomBranch("branch1");
logInAsProjectAdministrator(project);
- ComponentDto otherProject = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+ ComponentDto otherProject = ComponentTesting.newPrivateProjectDto();
SnapshotDto otherAnalysis = db.components().insertProjectAndSnapshot(otherProject);
expectedException.expect(IllegalArgumentException.class);
tester.insertProjectBranch(project, b -> b.setKey("branch1"));
logInAsProjectAdministrator(project);
- ComponentDto otherProject = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+ ComponentDto otherProject = ComponentTesting.newPrivateProjectDto();
SnapshotDto otherAnalysis = db.components().insertProjectAndSnapshot(otherProject);
expectedException.expect(IllegalArgumentException.class);
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
@Test
public void does_not_fail_and_has_no_effect_when_there_is_no_baseline_on_main_branch() {
- ComponentDto project = db.components().insertPublicProject(db.organizations().insert());
+ ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project);
SnapshotDto analysis = db.components().insertSnapshot(project);
logInAsProjectAdministrator(project);
@Test
public void does_not_fail_and_has_no_effect_when_there_is_no_baseline_on_non_main_branch() {
- ComponentDto project = db.components().insertPublicProject(db.organizations().insert());
+ ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project);
SnapshotDto analysis = db.components().insertSnapshot(project);
logInAsProjectAdministrator(project);
@Test
public void fail_when_branch_does_not_belong_to_project() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPublicProject(organization);
+ ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project);
- ComponentDto otherProject = db.components().insertPublicProject(organization);
+ ComponentDto otherProject = db.components().insertPublicProject();
ComponentDto otherBranch = db.components().insertProjectBranch(otherProject);
logInAsProjectAdministrator(project);
@Test
public void throw_ForbiddenException_if_not_project_administrator() {
- ComponentDto project = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+ ComponentDto project = ComponentTesting.newPrivateProjectDto();
SnapshotDto analysis = db.components().insertProjectAndSnapshot(project);
db.events().insertEvent(newEvent(analysis).setUuid("E1"));
userSession.logIn().addProjectPermission(UserRole.USER, project);
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ProjectLinkDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
@Test
public void fail_when_using_branch_db_key() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(organization);
+ ComponentDto project = db.components().insertPrivateProject();
userSession.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
@Test
public void fail_when_using_branch_db_uuid() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(organization);
+ ComponentDto project = db.components().insertPrivateProject();
userSession.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.ProjectLinkDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
@Test
public void fail_when_using_branch_db_key() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(organization);
+ ComponentDto project = db.components().insertPrivateProject();
userSession.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
@Test
public void fail_when_using_branch_db_uuid() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(organization);
+ ComponentDto project = db.components().insertPrivateProject();
userSession.logIn().addProjectPermission(UserRole.USER, project);
ComponentDto branch = db.components().insertProjectBranch(project);
import org.sonar.api.utils.System2;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
-import org.sonar.db.organization.OrganizationTesting;
import org.sonar.server.es.EsTester;
import org.sonar.server.measure.index.ProjectMeasuresDoc;
import org.sonar.server.measure.index.ProjectMeasuresIndex;
import static org.sonar.test.JsonAssert.assertJson;
public class SearchActionTest {
- private static final OrganizationDto ORG = OrganizationTesting.newOrganizationDto();
-
@Rule
public EsTester es = EsTester.create();
private static ProjectMeasuresDoc newDoc(ComponentDto project) {
return new ProjectMeasuresDoc()
- .setOrganizationUuid(project.getOrganizationUuid())
.setId(project.uuid())
.setKey(project.getDbKey())
.setName(project.name());
}
private static ProjectMeasuresDoc newDoc() {
- return newDoc(ComponentTesting.newPrivateProjectDto(ORG));
+ return newDoc(ComponentTesting.newPrivateProjectDto());
}
private SearchResponse call(@Nullable String textQuery, @Nullable Integer pageSize) {