getMapper(dbSession).updateDefaultQualityGate(organization.getUuid(), qualityGate.getUuid(), system2.now());
}
+ public boolean getNewProjectPrivate(DbSession dbSession, String organizationUuid) {
+ return getMapper(dbSession).selectNewProjectPrivateByUuid(organizationUuid);
+ }
+
public boolean getNewProjectPrivate(DbSession dbSession, OrganizationDto organization) {
return getMapper(dbSession).selectNewProjectPrivateByUuid(organization.getUuid());
}
return insertComponentImpl(ComponentTesting.newView(organizationDto, uuid), false, defaults());
}
+ public final ComponentDto insertPublicPortfolio() {
+ return insertPublicPortfolio(db.getDefaultOrganization(), defaults());
+ }
+
public final ComponentDto insertPublicPortfolio(OrganizationDto organization) {
return insertPublicPortfolio(organization, defaults());
}
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import static com.google.common.base.Preconditions.checkState;
return delegate.createComponentKey(projectKey, characteristics);
}
- ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, OrganizationDto organization,
+ ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey,
ComponentDto mainComponentDto, BranchDto mainComponentBranchDto) {
checkState(delegate != null, "Current edition does not support branch feature");
- return delegate.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+ return delegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto);
}
public abstract static class ComponentKey {
public abstract ComponentKey getMainBranchComponentKey();
}
-
private static final class ComponentKeyImpl extends ComponentKey {
private final String key;
private final String dbKey;
import org.sonar.db.ce.CeTaskCharacteristicDto;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.ce.queue.BranchSupport.ComponentKey;
@ServerSide
/**
* Creates the ComponentDto for the branch described in {@code componentKey} which belongs to the specified
- * {@code mainComponentDto} in the specified {@code organization}.
+ * {@code mainComponentDto}
*
* @throws IllegalArgumentException if arguments are inconsistent (such as {@code mainComponentDto} not having the same
* key as {@code componentKey.getKey()}, ...)
*/
- ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey,
- OrganizationDto organization, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto);
+ ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto,
+ BranchDto mainComponentBranchDto);
}
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.component.NewComponent;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.permission.PermissionTemplateService;
import org.sonar.server.user.UserSession;
-import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.defaultIfBlank;
import static org.sonar.server.component.NewComponent.newComponentBuilder;
private final PermissionTemplateService permissionTemplateService;
private final DbClient dbClient;
private final BranchSupport branchSupport;
+ private final DefaultOrganizationProvider defaultOrganizationProvider;
public ReportSubmitter(CeQueue queue, UserSession userSession, ComponentUpdater componentUpdater,
- PermissionTemplateService permissionTemplateService, DbClient dbClient, BranchSupport branchSupport) {
+ PermissionTemplateService permissionTemplateService, DbClient dbClient, BranchSupport branchSupport,
+ DefaultOrganizationProvider defaultOrganizationProvider) {
this.queue = queue;
this.userSession = userSession;
this.componentUpdater = componentUpdater;
this.permissionTemplateService = permissionTemplateService;
this.dbClient = dbClient;
this.branchSupport = branchSupport;
+ this.defaultOrganizationProvider = defaultOrganizationProvider;
}
- /**
- * @throws NotFoundException if the organization with the specified key does not exist
- * @throws IllegalArgumentException if the organization with the specified key is not the organization of the specified project (when it already exists in DB)
- */
- public CeTask submit(String organizationKey, String projectKey, @Nullable String projectName, Map<String, String> characteristics, InputStream reportInput) {
+ public CeTask submit(String projectKey, @Nullable String projectName, Map<String, String> characteristics, InputStream reportInput) {
try (DbSession dbSession = dbClient.openSession(false)) {
boolean projectCreated = false;
- OrganizationDto organizationDto = getOrganizationDtoOrFail(dbSession, organizationKey);
- // Note: when the main branch is analyzed, the characteristics may or may not have the branch name, so componentKey#isMainBranch is not reliable!
+ // Note: when the main branch is analyzed, the characteristics may or may not have the branch name, so componentKey#isMainBranch is not
+ // reliable!
BranchSupport.ComponentKey componentKey = branchSupport.createComponentKey(projectKey, characteristics);
Optional<ComponentDto> mainBranchComponentOpt = dbClient.componentDao().selectByKey(dbSession, componentKey.getKey());
ComponentDto mainBranchComponent;
if (mainBranchComponentOpt.isPresent()) {
mainBranchComponent = mainBranchComponentOpt.get();
validateProject(dbSession, mainBranchComponent, projectKey);
- ensureOrganizationIsConsistent(mainBranchComponent, organizationDto);
} else {
- mainBranchComponent = createProject(dbSession, organizationDto, componentKey.getMainBranchComponentKey(), projectName);
+ mainBranchComponent = createProject(dbSession, componentKey.getMainBranchComponentKey(), projectName);
projectCreated = true;
}
branchComponent = mainBranchComponent;
} else {
branchComponent = dbClient.componentDao().selectByKey(dbSession, componentKey.getDbKey())
- .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, organizationDto, mainBranchComponent, mainBranch));
+ .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch));
}
if (projectCreated) {
}
}
- private OrganizationDto getOrganizationDtoOrFail(DbSession dbSession, String organizationKey) {
- return dbClient.organizationDao().selectByKey(dbSession, organizationKey)
- .orElseThrow(() -> new NotFoundException(format("Organization with key '%s' does not exist", organizationKey)));
- }
-
private void validateProject(DbSession dbSession, ComponentDto component, String rawProjectKey) {
List<String> errors = new ArrayList<>();
// Project key is already used as a module of another project
ComponentDto anotherBaseProject = dbClient.componentDao().selectOrFailByUuid(dbSession, component.projectUuid());
errors.add(format("The project '%s' is already defined in SonarQube but as a module of project '%s'. "
- + "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
+ + "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
rawProjectKey, anotherBaseProject.getKey(), anotherBaseProject.getKey(), rawProjectKey));
}
if (!errors.isEmpty()) {
}
}
- private static void ensureOrganizationIsConsistent(ComponentDto project, OrganizationDto organizationDto) {
- checkArgument(project.getOrganizationUuid().equals(organizationDto.getUuid()),
- "Organization of component with key '%s' does not match specified organization '%s'",
- project.getDbKey(), organizationDto.getKey());
- }
-
- private ComponentDto createProject(DbSession dbSession, OrganizationDto organization, BranchSupport.ComponentKey componentKey, @Nullable String projectName) {
+ private ComponentDto createProject(DbSession dbSession, BranchSupport.ComponentKey componentKey, @Nullable String projectName) {
userSession.checkPermission(GlobalPermission.PROVISION_PROJECTS);
String userUuid = userSession.getUuid();
throw insufficientPrivilegesException();
}
- boolean newProjectPrivate = dbClient.organizationDao().getNewProjectPrivate(dbSession, organization);
+ // TODO:: remove once we move organization settings somewhere else
+ String defaultOrgUuid = defaultOrganizationProvider.get().getUuid();
+ boolean newProjectPrivate = dbClient.organizationDao().getNewProjectPrivate(dbSession, defaultOrgUuid);
NewComponent newProject = newComponentBuilder()
- .setOrganizationUuid(organization.getUuid())
+ .setOrganizationUuid(defaultOrgUuid)
.setKey(componentKey.getKey())
.setName(defaultIfBlank(projectName, componentKey.getKey()))
.setQualifier(Qualifiers.PROJECT)
private AnalysisStatusWsResponse.Component formatComponent(DbSession dbSession, ProjectDto project, @Nullable CeActivityDto lastActivity,
@Nullable String branchKey, @Nullable String pullRequestKey) {
AnalysisStatusWsResponse.Component.Builder builder = AnalysisStatusWsResponse.Component.newBuilder()
- .setOrganization(getOrganizationKey(dbSession, project))
.setKey(project.getKey())
.setName(project.getName());
return builder.build();
}
- private String getOrganizationKey(DbSession dbSession, ProjectDto project) {
- String organizationUuid = project.getOrganizationUuid();
- return dbClient.organizationDao().selectByUuid(dbSession, organizationUuid)
- .orElseThrow(() -> new IllegalStateException("Unknown organization: " + organizationUuid))
- .getKey();
- }
-
}
import org.sonar.ce.task.CeTask;
import org.sonar.db.ce.CeTaskCharacteristicDto;
import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
import org.sonar.server.ws.WsUtils;
import org.sonarqube.ws.Ce;
public class SubmitAction implements CeWsAction {
- private static final String PARAM_ORGANIZATION_KEY = "organization";
private static final String PARAM_PROJECT_KEY = "projectKey";
private static final String PARAM_PROJECT_NAME = "projectName";
private static final String PARAM_REPORT_DATA = "report";
private static final String PARAM_ANALYSIS_CHARACTERISTIC = "characteristic";
private final ReportSubmitter reportSubmitter;
- private final DefaultOrganizationProvider defaultOrganizationProvider;
- public SubmitAction(ReportSubmitter reportSubmitter, DefaultOrganizationProvider defaultOrganizationProvider) {
+ public SubmitAction(ReportSubmitter reportSubmitter) {
this.reportSubmitter = reportSubmitter;
- this.defaultOrganizationProvider = defaultOrganizationProvider;
}
@Override
.setHandler(this)
.setResponseExample(getClass().getResource("submit-example.json"));
- action.createParam(PARAM_ORGANIZATION_KEY)
- .setDescription("Key of the organization the project belongs to")
- .setExampleValue("my-org")
- .setSince("6.3")
- .setInternal(true);
-
action
.createParam(PARAM_PROJECT_KEY)
.setRequired(true)
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
- String organizationKey = wsRequest.getParam(PARAM_ORGANIZATION_KEY)
- .emptyAsNull()
- .or(defaultOrganizationProvider.get()::getKey);
String projectKey = wsRequest.mandatoryParam(PARAM_PROJECT_KEY);
String projectName = abbreviate(defaultIfBlank(wsRequest.param(PARAM_PROJECT_NAME), projectKey), MAX_COMPONENT_NAME_LENGTH);
Map<String, String> characteristics = parseTaskCharacteristics(wsRequest);
try (InputStream report = new BufferedInputStream(wsRequest.mandatoryParamAsPart(PARAM_REPORT_DATA).getInputStream())) {
- CeTask task = reportSubmitter.submit(organizationKey, projectKey, projectName, characteristics, report);
+ CeTask task = reportSubmitter.submit(projectKey, projectName, characteristics, report);
Ce.SubmitResponse submitResponse = Ce.SubmitResponse.newBuilder()
.setTaskId(task.getUuid())
.setProjectId(task.getComponent().get().getUuid())
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeTaskCharacteristicDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Common;
-import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
private Ce.Task formatQueue(CeQueueDto dto, DtoCache cache) {
Ce.Task.Builder builder = Ce.Task.newBuilder();
- String organizationKey = cache.getOrganizationKey(dto.getComponentUuid());
- ofNullable(organizationKey).ifPresent(builder::setOrganization);
if (dto.getComponentUuid() != null) {
builder.setComponentId(dto.getComponentUuid());
setComponent(builder, dto.getComponentUuid(), cache);
private static Ce.Task formatActivity(CeActivityDto dto, DtoCache cache, @Nullable String scannerContext, List<String> warnings) {
Ce.Task.Builder builder = Ce.Task.newBuilder();
- String organizationKey = cache.getOrganizationKey(dto.getComponentUuid());
- ofNullable(organizationKey).ifPresent(builder::setOrganization);
builder.setId(dto.getUuid());
builder.setStatus(Ce.TaskStatus.valueOf(dto.getStatus().name()));
builder.setType(dto.getTaskType());
private static class DtoCache {
private final Map<String, ComponentDto> componentsByUuid;
- private final Map<String, OrganizationDto> organizationsByUuid;
private final Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid;
private final Map<String, UserDto> usersByUuid;
- private DtoCache(Map<String, ComponentDto> componentsByUuid, Map<String, OrganizationDto> organizationsByUuid,
- Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid, Map<String, UserDto> usersByUuid) {
+ private DtoCache(Map<String, ComponentDto> componentsByUuid, Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid, Map<String, UserDto> usersByUuid) {
this.componentsByUuid = componentsByUuid;
- this.organizationsByUuid = organizationsByUuid;
this.characteristicsByTaskUuid = characteristicsByTaskUuid;
this.usersByUuid = usersByUuid;
}
.stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid));
Set<String> submitterUuids = ceQueueDtos.stream().map(CeQueueDto::getSubmitterUuid).filter(Objects::nonNull).collect(toSet());
Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(uniqueIndex(UserDto::getUuid));
- return new DtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid), characteristicsByTaskUuid, usersByUuid);
+ return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid);
}
private static Set<String> componentUuidsOfCeQueues(Collection<CeQueueDto> ceQueueDtos) {
.stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid));
Set<String> submitterUuids = ceActivityDtos.stream().map(CeActivityDto::getSubmitterUuid).filter(Objects::nonNull).collect(toSet());
Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(uniqueIndex(UserDto::getUuid));
- return new DtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid), characteristicsByTaskUuid, usersByUuid);
+ return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid);
}
private static Set<String> getComponentUuidsOfCeActivities(Collection<CeActivityDto> ceActivityDtos) {
.collect(toSet(ceActivityDtos.size()));
}
- private static Map<String, OrganizationDto> buildOrganizationsByUuid(DbClient dbClient, DbSession dbSession, Map<String, ComponentDto> componentsByUuid) {
- return dbClient.organizationDao().selectByUuids(
- dbSession,
- componentsByUuid.values().stream()
- .map(ComponentDto::getOrganizationUuid)
- .collect(toSet(componentsByUuid.size())))
- .stream()
- .collect(uniqueIndex(OrganizationDto::getUuid));
- }
-
@CheckForNull
ComponentDto getComponent(@Nullable String uuid) {
if (uuid == null) {
return componentsByUuid.get(uuid);
}
- @CheckForNull
- String getOrganizationKey(@Nullable String componentUuid) {
- if (componentUuid == null) {
- return null;
- }
- ComponentDto componentDto = componentsByUuid.get(componentUuid);
- if (componentDto == null) {
- return null;
- }
- String organizationUuid = componentDto.getOrganizationUuid();
- OrganizationDto organizationDto = organizationsByUuid.get(organizationUuid);
- checkState(organizationDto != null, "Organization with uuid '%s' not found", organizationUuid);
- return organizationDto.getKey();
- }
-
Optional<String> getBranchKey(String taskUuid) {
return characteristicsByTaskUuid.get(taskUuid).stream()
.filter(c -> c.getKey().equals(CeTaskCharacteristicDto.BRANCH_KEY))
{
"component": {
- "organization": "my-org-1",
"key": "com.github.kevinsawicki:http-request-parent",
"name": "HttpRequest",
"warnings": [
package org.sonar.server.ce.queue;
import com.google.common.collect.ImmutableMap;
-import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
-import java.util.function.BiConsumer;
import java.util.stream.IntStream;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.stubbing.Answer;
import org.sonar.api.utils.System2;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.favorite.FavoriteUpdater;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.permission.PermissionTemplateService;
import org.sonar.server.tester.UserSessionRule;
import static java.util.Collections.emptyMap;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-import static org.sonar.core.permission.GlobalPermissions.PROVISIONING;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.db.component.ComponentTesting.newBranchDto;
public class BranchReportSubmitterTest {
@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 final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
- private CeQueue queue = mock(CeQueueImpl.class);
- private ComponentUpdater componentUpdater = mock(ComponentUpdater.class);
- private PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
- private FavoriteUpdater favoriteUpdater = mock(FavoriteUpdater.class);
- private BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
- private BranchSupport branchSupport = spy(new BranchSupport(branchSupportDelegate));
+ private final CeQueue queue = mock(CeQueueImpl.class);
+ private final ComponentUpdater componentUpdater = mock(ComponentUpdater.class);
+ private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
+ private final FavoriteUpdater favoriteUpdater = mock(FavoriteUpdater.class);
+ private final BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
+ private final BranchSupport branchSupport = spy(new BranchSupport(branchSupportDelegate));
- private ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), branchSupport);
+ private final ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), branchSupport,
+ defaultOrganizationProvider);
@Test
public void submit_does_not_use_delegate_if_characteristics_are_empty() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPublicProject(organization);
+ ComponentDto project = db.components().insertPublicProject();
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
mockSuccessfulPrepareSubmitCall();
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
- underTest.submit(organization.getKey(), project.getDbKey(), project.name(), emptyMap(), reportInput);
+ underTest.submit(project.getDbKey(), project.name(), emptyMap(), reportInput);
verifyNoInteractions(branchSupportDelegate);
}
@Test
public void submit_a_report_on_existing_branch() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPublicProject(organization);
+ ComponentDto project = db.components().insertPublicProject();
ComponentDto branch = db.components().insertProjectBranch(project);
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
String taskUuid = mockSuccessfulPrepareSubmitCall();
- underTest.submit(organization.getKey(), project.getDbKey(), project.name(), randomCharacteristics, reportInput);
+ underTest.submit(project.getDbKey(), project.name(), randomCharacteristics, reportInput);
verifyNoInteractions(permissionTemplateService);
verifyNoInteractions(favoriteUpdater);
- verify(branchSupport, times(0)).createBranchComponent(any(), any(), any(), any(), any());
+ verify(branchSupport, times(0)).createBranchComponent(any(), any(), any(), any());
verify(branchSupportDelegate).createComponentKey(project.getDbKey(), randomCharacteristics);
- verify(branchSupportDelegate, times(0)).createBranchComponent(any(), any(), any(), any(), any());
+ verify(branchSupportDelegate, times(0)).createBranchComponent(any(), any(), any(), any());
verifyNoMoreInteractions(branchSupportDelegate);
verifyQueueSubmit(project, branch, user, randomCharacteristics, taskUuid);
}
@Test
public void submit_a_report_on_missing_branch_but_existing_project() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto existingProject = db.components().insertPublicProject(organization);
+ ComponentDto existingProject = db.components().insertPublicProject();
BranchDto exitingProjectMainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), existingProject.uuid()).get();
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, existingProject);
BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
when(branchSupportDelegate.createComponentKey(existingProject.getDbKey(), randomCharacteristics))
.thenReturn(componentKey);
- when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch)))
+ when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch)))
.thenReturn(createdBranch);
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
String taskUuid = mockSuccessfulPrepareSubmitCall();
- underTest.submit(organization.getKey(), existingProject.getDbKey(), existingProject.name(), randomCharacteristics, reportInput);
+ underTest.submit(existingProject.getDbKey(), existingProject.name(), randomCharacteristics, reportInput);
verifyNoInteractions(permissionTemplateService);
verifyNoInteractions(favoriteUpdater);
- verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch));
+ verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch));
verify(branchSupportDelegate).createComponentKey(existingProject.getDbKey(), randomCharacteristics);
- verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(existingProject), eq(exitingProjectMainBranch));
+ verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject),
+ eq(exitingProjectMainBranch));
verifyNoMoreInteractions(branchSupportDelegate);
verify(componentUpdater, times(0)).commitAndIndex(any(), any());
verifyQueueSubmit(existingProject, createdBranch, user, randomCharacteristics, taskUuid);
@Test
public void submit_report_on_missing_branch_of_missing_project_provisions_project_when_org_PROVISION_PROJECT_perm() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto nonExistingProject = newPrivateProjectDto(organization);
+ ComponentDto nonExistingProject = newPrivateProjectDto(db.getDefaultOrganization());
UserDto user = db.users().insertUser();
userSession.logIn(user)
.addPermission(PROVISION_PROJECTS)
.thenReturn(componentKey);
when(componentUpdater.createWithoutCommit(any(), any(), eq(user.getUuid()), any()))
.thenAnswer((Answer<ComponentDto>) invocation -> db.components().insertPrivateProject(nonExistingProject));
- when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), any()))
+ when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any()))
.thenReturn(createdBranch);
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(nonExistingProject.getKey())))
.thenReturn(true);
String taskUuid = mockSuccessfulPrepareSubmitCall();
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
- underTest.submit(organization.getKey(), nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
+ underTest.submit(nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
BranchDto exitingProjectMainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), nonExistingProject.uuid()).get();
- verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), eq(exitingProjectMainBranch));
+ verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), eq(exitingProjectMainBranch));
verify(branchSupportDelegate).createComponentKey(nonExistingProject.getDbKey(), randomCharacteristics);
- verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), eq(exitingProjectMainBranch));
+ verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject),
+ eq(exitingProjectMainBranch));
verifyNoMoreInteractions(branchSupportDelegate);
verifyQueueSubmit(nonExistingProject, createdBranch, user, randomCharacteristics, taskUuid);
verify(componentUpdater).commitAndIndex(any(DbSession.class), eq(nonExistingProject));
@Test
public void submit_fails_if_branch_support_delegate_createComponentKey_throws_an_exception() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPublicProject(organization);
+ ComponentDto project = db.components().insertPublicProject();
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
when(branchSupportDelegate.createComponentKey(any(), any())).thenThrow(expected);
try {
- underTest.submit(organization.getKey(), project.getDbKey(), project.name(), randomCharacteristics, reportInput);
+ underTest.submit(project.getDbKey(), project.name(), randomCharacteristics, reportInput);
fail("exception should have been thrown");
} catch (Exception e) {
assertThat(e).isSameAs(expected);
}
}
- @DataProvider
- public static Object[][] permissionsAllowingProjectProvisioning() {
- BiConsumer<ComponentDto, UserSessionRule> noProjectPerm = (cpt, userSession) -> {
- };
- BiConsumer<OrganizationDto, UserSessionRule> noOrgPerm = (cpt, userSession) -> {
- };
- BiConsumer<ComponentDto, UserSessionRule> provisionOnProject = (cpt, userSession) -> userSession.addProjectPermission(PROVISIONING, cpt);
- BiConsumer<OrganizationDto, UserSessionRule> provisionOnOrganization = (cpt, userSession) -> userSession.addPermission(PROVISION_PROJECTS);
- return new Object[][] {
- {provisionOnProject, noOrgPerm},
- {noProjectPerm, provisionOnOrganization},
- {provisionOnProject, provisionOnOrganization}
- };
- }
-
@Test
public void submit_report_on_missing_branch_of_missing_project_fails_with_ForbiddenException_if_only_scan_permission() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto nonExistingProject = newPrivateProjectDto(organization);
+ ComponentDto nonExistingProject = newPrivateProjectDto(db.getDefaultOrganization());
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, nonExistingProject);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
ComponentDto createdBranch = createButDoNotInsertBranch(nonExistingProject);
BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
- when(branchSupportDelegate.createComponentKey(nonExistingProject.getDbKey(), randomCharacteristics))
+ String nonExistingProjectDbKey = nonExistingProject.getDbKey();
+ when(branchSupportDelegate.createComponentKey(nonExistingProjectDbKey, randomCharacteristics))
.thenReturn(componentKey);
- when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(organization), eq(nonExistingProject), any()))
+ when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any()))
.thenReturn(createdBranch);
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- underTest.submit(organization.getKey(), nonExistingProject.getDbKey(), nonExistingProject.name(), randomCharacteristics, reportInput);
+ String name = nonExistingProject.name();
+ assertThatThrownBy(() -> underTest.submit(nonExistingProjectDbKey, name, randomCharacteristics, reportInput))
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
private static ComponentDto createButDoNotInsertBranch(ComponentDto project) {
import java.util.Map;
import java.util.Random;
import java.util.stream.IntStream;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.ce.queue.BranchSupport.ComponentKey;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
public class BranchSupportTest {
private static final Map<String, String> NO_CHARACTERISTICS = Collections.emptyMap();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- private BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
- private BranchSupport underTestNoBranch = new BranchSupport();
- private BranchSupport underTestWithBranch = new BranchSupport(branchSupportDelegate);
+ private final BranchSupportDelegate branchSupportDelegate = mock(BranchSupportDelegate.class);
+ private final BranchSupport underTestNoBranch = new BranchSupport();
+ private final BranchSupport underTestWithBranch = new BranchSupport(branchSupportDelegate);
@Test
public void createComponentKey_of_main_branch() {
public void createBranchComponent_fails_with_ISE_if_delegate_is_null() {
DbSession dbSession = mock(DbSession.class);
ComponentKey componentKey = mock(ComponentKey.class);
- OrganizationDto organization = new OrganizationDto();
ComponentDto mainComponentDto = new ComponentDto();
BranchDto mainComponentBranchDto = new BranchDto();
- expectedException.expect(IllegalStateException.class);
- expectedException.expectMessage("Current edition does not support branch feature");
-
- underTestNoBranch.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+ assertThatThrownBy(() -> underTestNoBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Current edition does not support branch feature");
}
@Test
public void createBranchComponent_delegates_to_delegate() {
DbSession dbSession = mock(DbSession.class);
ComponentKey componentKey = mock(ComponentKey.class);
- OrganizationDto organization = new OrganizationDto();
ComponentDto mainComponentDto = new ComponentDto();
ComponentDto expected = new ComponentDto();
BranchDto mainComponentBranchDto = new BranchDto();
- when(branchSupportDelegate.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto))
+ when(branchSupportDelegate.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto))
.thenReturn(expected);
- ComponentDto dto = underTestWithBranch.createBranchComponent(dbSession, componentKey, organization, mainComponentDto, mainComponentBranchDto);
+ ComponentDto dto = underTestWithBranch.createBranchComponent(dbSession, componentKey, mainComponentDto, mainComponentBranchDto);
assertThat(dto).isSameAs(expected);
}
public class CeQueueCleanerTest {
@Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
+ public final DbTester dbTester = DbTester.create(System2.INSTANCE);
- private ServerUpgradeStatus serverUpgradeStatus = mock(ServerUpgradeStatus.class);
- private CeQueue queue = mock(CeQueue.class);
- private MapSettings settings = new MapSettings();
+ private final ServerUpgradeStatus serverUpgradeStatus = mock(ServerUpgradeStatus.class);
+ private final CeQueue queue = mock(CeQueue.class);
+ private final MapSettings settings = new MapSettings();
@Test
public void start_does_not_reset_in_progress_tasks_to_pending() {
import java.util.Random;
import java.util.stream.IntStream;
import org.apache.commons.io.IOUtils;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.utils.System2;
import org.sonar.ce.queue.CeQueue;
import org.sonar.ce.queue.CeQueueImpl;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.es.TestProjectIndexers;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.favorite.FavoriteUpdater;
+import org.sonar.server.organization.DefaultOrganizationProvider;
+import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.permission.PermissionTemplateService;
import org.sonar.server.tester.UserSessionRule;
import static java.util.stream.IntStream.rangeClosed;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
private static final String TASK_UUID = "TASK_1";
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
- @Rule
- public DbTester db = DbTester.create();
+ public final DbTester db = DbTester.create();
- private String defaultOrganizationKey;
- private String defaultOrganizationUuid;
+ private final DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
- private CeQueue queue = mock(CeQueueImpl.class);
- private TestProjectIndexers projectIndexers = new TestProjectIndexers();
- private PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
- private ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), mock(System2.class), permissionTemplateService,
+ private final CeQueue queue = mock(CeQueueImpl.class);
+ private final TestProjectIndexers projectIndexers = new TestProjectIndexers();
+ private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
+ private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), mock(System2.class), permissionTemplateService,
new FavoriteUpdater(db.getDbClient()), projectIndexers, new SequenceUuidFactory());
- private BranchSupport ossEditionBranchSupport = new BranchSupport();
-
- private ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), ossEditionBranchSupport);
+ private final BranchSupport ossEditionBranchSupport = new BranchSupport();
- @Before
- public void setUp() {
- defaultOrganizationKey = db.getDefaultOrganization().getKey();
- defaultOrganizationUuid = db.getDefaultOrganization().getUuid();
- }
+ private final ReportSubmitter underTest = new ReportSubmitter(queue, userSession, componentUpdater, permissionTemplateService, db.getDbClient(), ossEditionBranchSupport,
+ defaultOrganizationProvider);
@Test
public void submit_with_characteristics_fails_with_ISE_when_no_branch_support_delegate() {
.collect(uniqueIndex(i -> randomAlphabetic(i + 10), i -> randomAlphabetic(i + 20)));
InputStream reportInput = IOUtils.toInputStream("{binary}", UTF_8);
- expectedException.expect(IllegalStateException.class);
- expectedException.expectMessage("Current edition does not support branch feature");
-
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, nonEmptyCharacteristics, reportInput);
+ assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, nonEmptyCharacteristics, reportInput))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Current edition does not support branch feature");
}
@Test
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(), any(), eq(PROJECT_KEY)))
.thenReturn(true);
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}", UTF_8));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}", UTF_8));
verifyReportIsPersisted(TASK_UUID);
}
@Test
public void submit_a_report_on_existing_project() {
- ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+ ComponentDto project = db.components().insertPrivateProject();
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
mockSuccessfulPrepareSubmitCall();
- underTest.submit(defaultOrganizationKey, project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8));
+ underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8));
verifyReportIsPersisted(TASK_UUID);
- verifyZeroInteractions(permissionTemplateService);
+ verifyNoInteractions(permissionTemplateService);
verify(queue).submit(argThat(submit -> submit.getType().equals(CeTaskTypes.REPORT)
&& submit.getComponent().filter(cpt -> cpt.getUuid().equals(project.uuid()) && cpt.getMainComponentUuid().equals(project.uuid())).isPresent()
&& submit.getSubmitterUuid().equals(user.getUuid())
@Test
public void provision_project_if_does_not_exist() {
- OrganizationDto organization = db.organizations().insert();
userSession
.addPermission(GlobalPermission.SCAN)
.addPermission(PROVISION_PROJECTS);
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
- underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
verifyReportIsPersisted(TASK_UUID);
@Test
public void add_project_as_favorite_when_project_creator_permission_on_permission_template() {
UserDto user = db.users().insertUser();
- OrganizationDto organization = db.organizations().insert();
userSession
.logIn(user)
.addPermission(GlobalPermission.SCAN)
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
- underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
assertThat(db.favorites().hasFavorite(createdProject, user.getUuid())).isTrue();
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(false);
mockSuccessfulPrepareSubmitCall();
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
assertThat(db.favorites().hasNoFavorite(createdProject)).isTrue();
public void do_no_add_favorite_when_already_100_favorite_projects_and_no_project_creator_permission_on_permission_template() {
UserDto user = db.users().insertUser();
rangeClosed(1, 100).forEach(i -> db.favorites().add(db.components().insertPrivateProject(), user.getUuid()));
- OrganizationDto organization = db.organizations().insert();
userSession
.logIn(user)
.addPermission(GlobalPermission.SCAN)
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY))).thenReturn(true);
when(permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(any(DbSession.class), any(ComponentDto.class))).thenReturn(true);
- underTest.submit(organization.getKey(), PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
ComponentDto createdProject = db.getDbClient().componentDao().selectByKey(db.getSession(), PROJECT_KEY).get();
assertThat(db.favorites().hasNoFavorite(createdProject)).isTrue();
}
@Test
- public void submit_a_report_on_new_project_with_scan_permission_on_organization() {
+ public void submit_a_report_on_new_project_with_scan_permission() {
userSession
.addPermission(GlobalPermission.SCAN)
.addPermission(PROVISION_PROJECTS);
when(permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(any(DbSession.class), any(), eq(PROJECT_KEY)))
.thenReturn(true);
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
verify(queue).submit(any(CeTaskSubmit.class));
}
@Test
- public void user_with_scan_permission_on_organization_is_allowed_to_submit_a_report_on_existing_project() {
- OrganizationDto org = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(org);
+ public void user_with_scan_permission_is_allowed_to_submit_a_report_on_existing_project() {
+ ComponentDto project = db.components().insertPrivateProject();
userSession.addPermission(SCAN);
mockSuccessfulPrepareSubmitCall();
- underTest.submit(org.getKey(), project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
verify(queue).submit(any(CeTaskSubmit.class));
}
@Test
public void submit_a_report_on_existing_project_with_project_scan_permission() {
- ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+ ComponentDto project = db.components().insertPrivateProject();
userSession.addProjectPermission(SCAN_EXECUTION, project);
mockSuccessfulPrepareSubmitCall();
- underTest.submit(defaultOrganizationKey, project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+ underTest.submit(project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
verify(queue).submit(any(CeTaskSubmit.class));
}
- @Test
- public void fail_with_NotFoundException_if_organization_with_specified_key_does_not_exist() {
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage("Organization with key 'fop' does not exist");
-
- underTest.submit("fop", PROJECT_KEY, null, emptyMap(), null /* method will fail before parameter is used */);
- }
-
- @Test
- public void fail_with_organizationKey_does_not_match_organization_of_specified_component() {
- userSession.logIn().setRoot();
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project = db.components().insertPrivateProject(organization);
- mockSuccessfulPrepareSubmitCall();
-
- underTest.submit(organization.getKey(), project.getDbKey(), project.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
- }
-
@Test
public void fail_if_component_is_not_a_project() {
- ComponentDto component = db.components().insertPublicPortfolio(db.getDefaultOrganization());
+ ComponentDto component = db.components().insertPublicPortfolio();
userSession.logIn().addProjectPermission(SCAN_EXECUTION, component);
mockSuccessfulPrepareSubmitCall();
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage(format("Component '%s' is not a project", component.getKey()));
-
- underTest.submit(defaultOrganizationKey, component.getDbKey(), component.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
+ String dbKey = component.getDbKey();
+ String name = component.name();
+ Map<String, String> emptyMap = emptyMap();
+ InputStream stream = IOUtils.toInputStream("{binary}", UTF_8);
+ assertThatThrownBy(() -> underTest.submit(dbKey, name, emptyMap, stream))
+ .isInstanceOf(BadRequestException.class)
+ .hasMessage(format("Component '%s' is not a project", component.getKey()));
}
@Test
public void fail_if_project_key_already_exists_as_module() {
- ComponentDto project = db.components().insertPrivateProject(db.getDefaultOrganization());
+ ComponentDto project = db.components().insertPrivateProject();
ComponentDto module = db.components().insertComponent(newModuleDto(project));
userSession.logIn().addProjectPermission(SCAN_EXECUTION, project);
mockSuccessfulPrepareSubmitCall();
- try {
- underTest.submit(defaultOrganizationKey, module.getDbKey(), module.name(), emptyMap(), IOUtils.toInputStream("{binary}"));
- fail();
- } catch (BadRequestException e) {
- assertThat(e.errors()).contains(
- format("The project '%s' is already defined in SonarQube but as a module of project '%s'. " +
- "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
- module.getKey(), project.getKey(), project.getKey(), module.getKey()));
- }
+ String moduleDbKey = module.getDbKey();
+ String name = module.name();
+ Map<String, String> emptyMap = emptyMap();
+ InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+ assertThatThrownBy(() -> underTest.submit(moduleDbKey, name, emptyMap, inputStream))
+ .isInstanceOf(BadRequestException.class)
+ .extracting(throwable -> ((BadRequestException) throwable).errors())
+ .asList()
+ .contains(format("The project '%s' is already defined in SonarQube but as a module of project '%s'. " +
+ "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.",
+ module.getKey(), project.getKey(), project.getKey(), module.getKey()));
}
@Test
public void fail_with_forbidden_exception_when_no_scan_permission() {
- expectedException.expect(ForbiddenException.class);
-
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ Map<String, String> emptyMap = emptyMap();
+ InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+ assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap, inputStream))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_with_forbidden_exception_on_new_project_when_only_project_scan_permission() {
- ComponentDto component = ComponentTesting.newPrivateProjectDto(db.getDefaultOrganization(), PROJECT_UUID);
+ ComponentDto component = db.components().insertPrivateProject(PROJECT_UUID);
userSession.addProjectPermission(SCAN_EXECUTION, component);
mockSuccessfulPrepareSubmitCall();
- expectedException.expect(ForbiddenException.class);
- underTest.submit(defaultOrganizationKey, PROJECT_KEY, PROJECT_NAME, emptyMap(), IOUtils.toInputStream("{binary}"));
+ Map<String, String> emptyMap = emptyMap();
+ InputStream inputStream = IOUtils.toInputStream("{binary}", UTF_8);
+ assertThatThrownBy(() -> underTest.submit(PROJECT_KEY, PROJECT_NAME, emptyMap, inputStream))
+ .isInstanceOf(ForbiddenException.class);
}
private void verifyReportIsPersisted(String taskUuid) {
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
private static final long EXECUTED_AT = System2.INSTANCE.now();
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
@Test
public void get_all_past_activity() {
logInAsSystemAdministrator();
- OrganizationDto org1 = db.organizations().insert();
- ComponentDto project1 = db.components().insertPrivateProject(org1);
- OrganizationDto org2 = db.organizations().insert();
- ComponentDto project2 = db.components().insertPrivateProject(org2);
+ ComponentDto project1 = db.components().insertPrivateProject();
+ ComponentDto project2 = db.components().insertPrivateProject();
SnapshotDto analysisProject1 = db.components().insertSnapshot(project1);
insertActivity("T1", project1, SUCCESS, analysisProject1);
insertActivity("T2", project2, FAILED, null);
assertThat(activityResponse.getTasksCount()).isEqualTo(2);
// chronological order, from newest to oldest
Task task = activityResponse.getTasks(0);
- assertThat(task.getOrganization()).isEqualTo(org2.getKey());
assertThat(task.getId()).isEqualTo("T2");
assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.FAILED);
assertThat(task.getComponentId()).isEqualTo(project2.uuid());
assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.SUCCESS);
assertThat(task.getComponentId()).isEqualTo(project1.uuid());
assertThat(task.getLogs()).isFalse();
- assertThat(task.getOrganization()).isEqualTo(org1.getKey());
assertThat(task.getWarningCount()).isZero();
}
ComponentDto project = db.components().insertPrivateProject();
userSession.anonymous();
- expectedException.expect(UnauthorizedException.class);
- expectedException.expectMessage("Authentication is required");
-
- call(ws.newRequest().setParam("componentId", project.uuid()));
+ TestRequest request = ws.newRequest().setParam("componentId", project.uuid());
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(UnauthorizedException.class)
+ .hasMessage("Authentication is required");
}
@Test
insertActivity("T1", view, SUCCESS);
userSession.logIn().addProjectPermission(UserRole.ADMIN, view);
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- call(ws.newRequest().setParam(Param.TEXT_QUERY, "T1"));
+ TestRequest request = ws.newRequest().setParam(TEXT_QUERY, "T1");
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
@Test
@Test
public void fail_if_both_component_id_and_component_key_provided() {
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("componentId and component must not be set at the same time");
-
- ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam("componentId", "ID1")
.setParam("component", "apache")
- .setMediaType(MediaTypes.PROTOBUF)
- .execute();
+ .setMediaType(MediaTypes.PROTOBUF);
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(BadRequestException.class)
+ .hasMessage("componentId and component must not be set at the same time");
}
@Test
public void fail_if_both_filters_on_component_key_and_name() {
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("component and q must not be set at the same time");
-
- ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam("q", "apache")
.setParam("component", "apache")
- .setMediaType(MediaTypes.PROTOBUF)
- .execute();
+ .setMediaType(MediaTypes.PROTOBUF);
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(BadRequestException.class)
+ .hasMessage("component and q must not be set at the same time");
}
@Test
public void fail_if_both_filters_on_component_id_and_name() {
- expectedException.expect(BadRequestException.class);
- expectedException.expectMessage("componentId and q must not be set at the same time");
-
- ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam("componentId", "ID1")
.setParam("q", "apache")
- .setMediaType(MediaTypes.PROTOBUF)
- .execute();
+ .setMediaType(MediaTypes.PROTOBUF);
+
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(BadRequestException.class)
+ .hasMessage("componentId and q must not be set at the same time");
}
@Test
public void fail_if_page_size_greater_than_1000() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("'ps' value (1001) must be less than 1000");
+ TestRequest request = ws.newRequest()
+ .setParam(Param.PAGE_SIZE, "1001");
- ws.newRequest()
- .setParam(Param.PAGE_SIZE, "1001")
- .execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("'ps' value (1001) must be less than 1000");
}
@Test
public void fail_if_date_is_not_well_formatted() {
logInAsSystemAdministrator();
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Date 'ill-formatted-date' cannot be parsed as either a date or date+time");
+ TestRequest request = ws.newRequest()
+ .setParam(PARAM_MAX_EXECUTED_AT, "ill-formatted-date");
- ws.newRequest()
- .setParam(PARAM_MAX_EXECUTED_AT, "ill-formatted-date")
- .execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Date 'ill-formatted-date' cannot be parsed as either a date or date+time");
}
@Test
public void throws_IAE_if_pageSize_is_0() {
logInAsSystemAdministrator();
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("page size must be >= 1");
-
- call(ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam(Param.PAGE_SIZE, Integer.toString(0))
- .setParam(PARAM_STATUS, "SUCCESS,FAILED,CANCELED,IN_PROGRESS,PENDING"));
+ .setParam(PARAM_STATUS, "SUCCESS,FAILED,CANCELED,IN_PROGRESS,PENDING");
+ assertThatThrownBy(() -> call(request))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("page size must be >= 1");
+
}
@Test
public void fail_when_project_does_not_exist() {
logInAsSystemAdministrator();
- expectedException.expect(NotFoundException.class);
- expectedException.expectMessage("Component 'unknown' does not exist");
-
- ws.newRequest()
- .setParam(PARAM_COMPONENT_ID, "unknown")
- .execute();
+ TestRequest request = ws.newRequest().setParam(PARAM_COMPONENT_ID, "unknown");
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class)
+ .hasMessage("Component 'unknown' does not exist");
}
private void assertPage(int pageSize, List<String> expectedOrderedTaskIds) {
}
@Test
- public void filter_out_duplicate_tasks_in_progress_and_success(){
+ public void filter_out_duplicate_tasks_in_progress_and_success() {
logInAsSystemAdministrator();
ComponentDto project1 = db.components().insertPrivateProject();
ComponentDto project2 = db.components().insertPrivateProject();
assertThat(response.getTasksList())
.extracting(Task::getId)
- .containsExactlyInAnyOrder("T1","T2","T3");
+ .containsExactlyInAnyOrder("T1", "T2", "T3");
}
private void logInAsSystemAdministrator() {
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.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonarqube.ws.Ce;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.ce.CeQueueTesting.newCeQueueDto;
public class ActivityStatusActionTest {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone().logIn().setSystemAdministrator();
@Rule
public void status_for_a_project_as_project_admin() {
String projectUuid = "project-uuid";
String anotherProjectUuid = "another-project-uuid";
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto project = newPrivateProjectDto(organizationDto, projectUuid);
- ComponentDto anotherProject = newPrivateProjectDto(organizationDto, anotherProjectUuid);
+ ComponentDto project = newPrivateProjectDto(db.getDefaultOrganization(), projectUuid);
+ ComponentDto anotherProject = newPrivateProjectDto(db.getDefaultOrganization(), anotherProjectUuid);
db.components().insertComponent(project);
- db.components().insertComponent(newPrivateProjectDto(organizationDto, anotherProjectUuid));
+ db.components().insertComponent(newPrivateProjectDto(db.getDefaultOrganization(), anotherProjectUuid));
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
// pending tasks returned
insertInQueue(CeQueueDto.Status.PENDING, project);
@Test
public void add_pending_time() {
String projectUuid = "project-uuid";
- OrganizationDto organizationDto = db.organizations().insert();
- ComponentDto project = newPrivateProjectDto(organizationDto, projectUuid);
+ ComponentDto project = newPrivateProjectDto(db.getDefaultOrganization(), projectUuid);
db.components().insertComponent(project);
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
@Test
public void fail_if_component_uuid_and_key_are_provided() {
- ComponentDto project = ComponentTesting.newPrivateProjectDto(db.organizations().insert());
+ ComponentDto project = ComponentTesting.newPrivateProjectDto();
db.components().insertComponent(project);
- expectedException.expect(IllegalArgumentException.class);
- callByComponentUuidOrComponentKey(project.uuid(), project.getDbKey());
+ String uuid = project.uuid();
+ String dbKey = project.getDbKey();
+ assertThatThrownBy(() -> callByComponentUuidOrComponentKey(uuid, dbKey))
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_component_uuid_is_unknown() {
- expectedException.expect(NotFoundException.class);
-
- call("unknown-uuid");
+ assertThatThrownBy(() -> call("unknown-uuid"))
+ .isInstanceOf(NotFoundException.class);
}
@Test
public void fail_if_component_key_is_unknown() {
- expectedException.expect(NotFoundException.class);
-
- callByComponentKey("unknown-key");
+ assertThatThrownBy(() -> callByComponentKey("unknown-key"))
+ .isInstanceOf(NotFoundException.class);
}
@Test
public void throw_ForbiddenException_if_not_root() {
userSession.logIn();
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- call();
+ assertThatThrownBy(this::call)
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
@Test
userSession.logIn();
ComponentDto project = db.components().insertPrivateProject();
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
-
- callByComponentKey(project.getDbKey());
+ String dbKey = project.getDbKey();
+ assertThatThrownBy(() -> callByComponentKey(dbKey))
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
private void insertInQueue(CeQueueDto.Status status, @Nullable ComponentDto componentDto) {
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Ce.AnalysisStatusWsResponse.Warning;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
import static org.sonar.db.ce.CeTaskTypes.REPORT;
private static int counter = 1;
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
@Test
public void allows_unauthenticated_access() {
- ComponentDto project = db.components().insertPublicProject(db.getDefaultOrganization());
+ ComponentDto project = db.components().insertPublicProject();
userSession.registerComponents(project);
SnapshotDto analysis = db.components().insertSnapshot(project);
CeActivityDto activity = insertActivity("task-uuid" + counter++, project, SUCCESS, analysis, REPORT);
@Test
public void json_example() {
- OrganizationDto organization = db.organizations().insert(o -> o.setKey("my-org-1"));
- ComponentDto project = db.components().insertPrivateProject(organization,
- p -> p.setDbKey("com.github.kevinsawicki:http-request-parent")
- .setName("HttpRequest"));
+ ComponentDto project = db.components().insertPrivateProject(p -> p.setDbKey("com.github.kevinsawicki:http-request-parent")
+ .setName("HttpRequest"));
SnapshotDto analysis = db.components().insertSnapshot(project);
CeActivityDto activity = insertActivity("task-uuid" + counter++, project, SUCCESS, analysis, REPORT);
CeTaskMessageDto ceTaskMessage = new CeTaskMessageDto()
@Test
public void fail_if_component_key_not_provided() {
- expectedException.expect(IllegalArgumentException.class);
-
- ws.newRequest().execute();
+ TestRequest request = ws.newRequest();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
public void fail_if_component_key_is_unknown() {
- expectedException.expect(NotFoundException.class);
-
- ws.newRequest().setParam(PARAM_COMPONENT, "nonexistent").execute();
+ TestRequest request = ws.newRequest().setParam(PARAM_COMPONENT, "nonexistent");
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class);
}
@Test
public void fail_if_both_branch_and_pullRequest_are_specified() {
- expectedException.expect(BadRequestException.class);
-
- ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam(PARAM_COMPONENT, "dummy")
.setParam(PARAM_BRANCH, "feature1")
- .setParam(PARAM_PULL_REQUEST, "pr1")
- .execute();
+ .setParam(PARAM_PULL_REQUEST, "pr1");
+
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(BadRequestException.class);
}
private CeTaskMessageDto createTaskMessage(CeActivityDto activity, String warning) {
import org.mockito.Mockito;
import org.sonar.api.server.ws.WebService;
import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@Test
public void define() {
- CeWsAction wsAction = new SubmitAction(mock(ReportSubmitter.class), mock(DefaultOrganizationProvider.class));
+ CeWsAction wsAction = new SubmitAction(mock(ReportSubmitter.class));
CeWs ws = new CeWs(wsAction);
WebService.Context context = mock(WebService.Context.class, Mockito.RETURNS_DEEP_STUBS);
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Common;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.sonar.db.ce.CeActivityDto.Status.SUCCESS;
import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS;
public class ComponentActionTest {
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
@Test
public void project_tasks() {
- OrganizationDto organization = db.organizations().insert();
- ComponentDto project1 = db.components().insertPrivateProject(organization);
+ ComponentDto project1 = db.components().insertPrivateProject();
SnapshotDto analysisProject1 = db.components().insertSnapshot(project1);
- ComponentDto project2 = db.components().insertPrivateProject(organization);
+ ComponentDto project2 = db.components().insertPrivateProject();
userSession.addProjectPermission(UserRole.USER, project1);
insertActivity("T1", project1, CeActivityDto.Status.SUCCESS, analysisProject1);
insertActivity("T2", project2, CeActivityDto.Status.FAILED, null);
assertThat(current.hasAnalysisId()).isFalse();
assertThat(current.getWarningCount()).isZero();
assertThat(current.getWarningsList()).isEmpty();
- assertThat(response.getQueueList())
- .extracting(Ce.Task::getOrganization)
- .containsOnly(organization.getKey());
- assertThat(current.getOrganization()).isEqualTo(organization.getKey());
}
@Test
@Test
public void fail_with_404_when_component_does_not_exist() {
- expectedException.expect(NotFoundException.class);
- ws.newRequest()
+ TestRequest request = ws.newRequest()
.setParam(PARAM_COMPONENT, "UNKNOWN")
- .setMediaType(MediaTypes.PROTOBUF)
- .execute();
+ .setMediaType(MediaTypes.PROTOBUF);
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class);
}
@Test
ComponentDto project = db.components().insertPrivateProject();
userSession.logIn();
- expectedException.expect(ForbiddenException.class);
- expectedException.expectMessage("Insufficient privileges");
+ TestRequest request = ws.newRequest()
+ .setParam(PARAM_COMPONENT, project.getKey());
- ws.newRequest()
- .setParam(PARAM_COMPONENT, project.getKey())
- .execute();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(ForbiddenException.class)
+ .hasMessage("Insufficient privileges");
}
@Test
public void fail_when_no_component_parameter() {
- expectedException.expect(IllegalArgumentException.class);
logInWithBrowsePermission(db.components().insertPrivateProject());
- ws.newRequest().execute();
+ TestRequest request = ws.newRequest();
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(IllegalArgumentException.class);
}
private void logInWithBrowsePermission(ComponentDto project) {
import org.sonar.ce.task.CeTask;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.server.ce.queue.ReportSubmitter;
-import org.sonar.server.organization.DefaultOrganizationProvider;
-import org.sonar.server.organization.TestDefaultOrganizationProvider;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonar.test.JsonAssert;
.setSubmitter(new CeTask.User("UUID_1", "LOGIN_1"))
.build();
- private ArgumentCaptor<Map<String, String>> map = ArgumentCaptor.forClass(Map.class);
- private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.fromUuid("org1");
- private String organizationKey = defaultOrganizationProvider.get().getKey();
- private ReportSubmitter reportSubmitter = mock(ReportSubmitter.class);
- private SubmitAction underTest = new SubmitAction(reportSubmitter, defaultOrganizationProvider);
- private WsActionTester tester = new WsActionTester(underTest);
+ private final ArgumentCaptor<Map<String, String>> map = ArgumentCaptor.forClass(Map.class);
+
+ private final ReportSubmitter reportSubmitter = mock(ReportSubmitter.class);
+ private final SubmitAction underTest = new SubmitAction(reportSubmitter);
+ private final WsActionTester tester = new WsActionTester(underTest);
@Test
public void submit_task_to_the_queue_and_ask_for_immediate_processing() {
- when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+ when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
Ce.SubmitResponse submitResponse = tester.newRequest()
.setParam("projectKey", "my_project")
.setMethod("POST")
.executeProtobuf(Ce.SubmitResponse.class);
- verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any());
+ verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), anyMap(), any());
assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
assertThat(submitResponse.getProjectId()).isEqualTo(PROJECT_UUID);
@Test
public void submit_task_with_characteristics() {
- when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+ when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
String[] characteristics = {"branch=foo", "pullRequest=123", "unsupported=bar"};
Ce.SubmitResponse submitResponse = tester.newRequest()
.executeProtobuf(Ce.SubmitResponse.class);
assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
- verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("My Project"), map.capture(), any());
+ verify(reportSubmitter).submit(eq("my_project"), eq("My Project"), map.capture(), any());
// unsupported characteristics are ignored
assertThat(map.getValue()).containsExactly(entry("branch", "foo"), entry("pullRequest", "123"));
public void abbreviate_long_name() {
String longName = Strings.repeat("a", 1_000);
String expectedName = Strings.repeat("a", 497) + "...";
- when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq(expectedName), anyMap(), any())).thenReturn(A_CE_TASK);
+ when(reportSubmitter.submit(eq("my_project"), eq(expectedName), anyMap(), any())).thenReturn(A_CE_TASK);
Ce.SubmitResponse submitResponse = tester.newRequest()
.setParam("projectKey", "my_project")
.setMethod("POST")
.executeProtobuf(Ce.SubmitResponse.class);
- verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq(expectedName), anyMap(), any());
+ verify(reportSubmitter).submit(eq("my_project"), eq(expectedName), anyMap(), any());
assertThat(submitResponse.getTaskId()).isEqualTo("TASK_1");
assertThat(submitResponse.getProjectId()).isEqualTo(PROJECT_UUID);
@Test
public void test_example_json_response() {
- when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
+ when(reportSubmitter.submit(eq("my_project"), eq("My Project"), anyMap(), any())).thenReturn(A_CE_TASK);
TestResponse wsResponse = tester.newRequest()
.setParam("projectKey", "my_project")
*/
@Test
public void project_name_is_optional() {
- when(reportSubmitter.submit(eq(organizationKey), eq("my_project"), eq("my_project"), anyMap(), any())).thenReturn(A_CE_TASK);
+ when(reportSubmitter.submit(eq("my_project"), eq("my_project"), anyMap(), any())).thenReturn(A_CE_TASK);
tester.newRequest()
.setParam("projectKey", "my_project")
.setMethod("POST")
.execute();
- verify(reportSubmitter).submit(eq(organizationKey), eq("my_project"), eq("my_project"), anyMap(), any());
+ verify(reportSubmitter).submit(eq("my_project"), eq("my_project"), anyMap(), any());
}
}
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.ce.CeTaskMessageType;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.db.component.ComponentDto;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
+import org.sonar.server.ws.TestRequest;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Common;
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.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY;
import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY;
private static final String SOME_TASK_UUID = "TASK_1";
@Rule
- public UserSessionRule userSession = UserSessionRule.standalone();
+ public final UserSessionRule userSession = UserSessionRule.standalone();
@Rule
- public ExpectedException expectedException = ExpectedException.none();
+ public final DbTester db = DbTester.create(System2.INSTANCE);
- @Rule
- public DbTester db = DbTester.create(System2.INSTANCE);
-
- private OrganizationDto organization;
- private ComponentDto privateProject;
- private ComponentDto publicProject;
private final TaskFormatter formatter = new TaskFormatter(db.getDbClient(), System2.INSTANCE);
private final TaskAction underTest = new TaskAction(db.getDbClient(), formatter, userSession);
private final WsActionTester ws = new WsActionTester(underTest);
+ private ComponentDto privateProject;
+ private ComponentDto publicProject;
+
@Before
public void setUp() {
- organization = db.organizations().insert();
- privateProject = db.components().insertPrivateProject(organization);
- publicProject = db.components().insertPublicProject(organization);
+ privateProject = db.components().insertPrivateProject();
+ publicProject = db.components().insertPublicProject();
}
@Test
Ce.TaskResponse taskResponse = ws.newRequest()
.setParam("id", SOME_TASK_UUID)
.executeProtobuf(Ce.TaskResponse.class);
- assertThat(taskResponse.getTask().getOrganization()).isEqualTo(organization.getKey());
assertThat(taskResponse.getTask().getId()).isEqualTo(SOME_TASK_UUID);
assertThat(taskResponse.getTask().getStatus()).isEqualTo(Ce.TaskStatus.PENDING);
assertThat(taskResponse.getTask().getSubmitterLogin()).isEqualTo(user.getLogin());
.setParam("id", SOME_TASK_UUID)
.executeProtobuf(Ce.TaskResponse.class);
Ce.Task task = taskResponse.getTask();
- assertThat(task.getOrganization()).isEqualTo(organization.getKey());
assertThat(task.getId()).isEqualTo(SOME_TASK_UUID);
assertThat(task.getStatus()).isEqualTo(Ce.TaskStatus.FAILED);
assertThat(task.getComponentId()).isEqualTo(privateProject.uuid());
public void throw_NotFoundException_if_id_does_not_exist() {
logInAsRoot();
- expectedException.expect(NotFoundException.class);
-
- ws.newRequest()
- .setParam("id", "DOES_NOT_EXIST")
- .execute();
+ TestRequest request = ws.newRequest()
+ .setParam("id", "DOES_NOT_EXIST");
+ assertThatThrownBy(request::execute)
+ .isInstanceOf(NotFoundException.class);
}
@Test
userSession.logIn().registerComponents(publicProject);
CeQueueDto task = createAndPersistQueueTask(publicProject, user);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
userSession.logIn().addProjectPermission(UserRole.USER, privateProject);
CeQueueDto task = createAndPersistQueueTask(privateProject, user);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
}
@Test
- public void get_project_queue_task_with_scan_permission_on_organization_but_not_on_project() {
+ public void get_project_queue_task_with_scan_permission_but_not_on_project() {
UserDto user = db.users().insertUser();
userSession.logIn(user).addPermission(SCAN);
CeQueueDto task = createAndPersistQueueTask(privateProject, user);
userSession.logIn(user);
CeQueueDto task = createAndPersistQueueTask(privateProject, user);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
userSession.logIn(user).setNonSystemAdministrator();
CeQueueDto task = createAndPersistQueueTask(null, user);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
userSession.logIn().registerComponents(publicProject);
CeActivityDto task = createAndPersistArchivedTask(publicProject);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
- public void get_project_archived_task_with_scan_permission_on_organization_but_not_on_project() {
+ public void get_project_archived_task_with_scan_permission_but_not_on_project() {
userSession.logIn().addPermission(SCAN);
CeActivityDto task = createAndPersistArchivedTask(privateProject);
userSession.logIn();
CeActivityDto task = createAndPersistArchivedTask(privateProject);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
userSession.logIn().setNonSystemAdministrator();
CeActivityDto task = createAndPersistArchivedTask(null);
- expectedException.expect(ForbiddenException.class);
-
- call(task.getUuid());
+ String uuid = task.getUuid();
+ assertThatThrownBy(() -> call(uuid))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
public void get_warnings_on_public_project_archived_task_if_not_admin_fails_with_ForbiddenException() {
userSession.logIn().registerComponents(publicProject);
- expectedException.expect(ForbiddenException.class);
-
- getWarningsImpl(createAndPersistArchivedTask(publicProject));
+ CeActivityDto persistArchivedTask = createAndPersistArchivedTask(publicProject);
+ assertThatThrownBy(() -> getWarningsImpl(persistArchivedTask))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
public void get_warnings_on_private_project_archived_task_if_user_fails_with_ForbiddenException() {
userSession.logIn().addProjectPermission(UserRole.USER, privateProject);
- expectedException.expect(ForbiddenException.class);
-
- getWarningsImpl(createAndPersistArchivedTask(privateProject));
+ CeActivityDto persistArchivedTask = createAndPersistArchivedTask(privateProject);
+ assertThatThrownBy(() -> getWarningsImpl(persistArchivedTask))
+ .isInstanceOf(ForbiddenException.class);
}
@Test
}
@Test
- public void get_warnings_on_private_project_archived_task_if_scan_on_organization() {
+ public void get_warnings_on_private_project_archived_task_if_global_scan_permission() {
userSession.logIn().addPermission(GlobalPermission.SCAN);
getWarningsImpl(createAndPersistArchivedTask(privateProject));
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
+import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.ce.CeTaskTypes;
-import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.UserDto;
import org.sonarqube.ws.Ce;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- private int warningCount = new Random().nextInt(10);
+ private final int warningCount = new Random().nextInt(10);
- private System2 system2 = mock(System2.class);
- private TaskFormatter underTest = new TaskFormatter(db.getDbClient(), system2);
+ private final System2 system2 = mock(System2.class);
+ private final TaskFormatter underTest = new TaskFormatter(db.getDbClient(), system2);
@Test
public void formatQueue_without_component() {
@Test
public void formatQueue_with_component_and_other_fields() {
String uuid = "COMPONENT_UUID";
- OrganizationDto organizationDto = db.organizations().insert();
- db.components().insertPrivateProject(organizationDto, (t) -> t.setUuid(uuid).setDbKey("COMPONENT_KEY").setName("Component Name"));
+ db.components().insertPrivateProject((t) -> t.setUuid(uuid).setDbKey("COMPONENT_KEY").setName("Component Name"));
UserDto user = db.users().insertUser();
CeQueueDto dto = new CeQueueDto();
UserDto user = db.users().insertUser();
CeActivityDto dto = newActivity("UUID", "COMPONENT_UUID", CeActivityDto.Status.FAILED, user);
- expectedException.expect(NullPointerException.class);
-
- underTest.formatActivity(db.getSession(), dto, "foo", null);
+ DbSession dbSession = db.getSession();
+ assertThatThrownBy(() -> underTest.formatActivity(dbSession, dto, "foo", null))
+ .isInstanceOf(NullPointerException.class);
}
@Test
optional Component component = 1;
message Component {
- optional string organization = 1;
- optional string key = 2;
- optional string name = 3;
- repeated Warning warnings = 4;
- optional string branch = 5;
- optional string pullRequest = 6;
+ optional string key = 1;
+ optional string name = 2;
+ repeated Warning warnings = 3;
+ optional string branch = 4;
+ optional string pullRequest = 5;
}
message Warning {
optional string errorStacktrace = 17;
optional string scannerContext = 18;
optional bool hasScannerContext = 19;
- optional string organization = 20;
- optional string branch = 21;
- optional sonarqube.ws.commons.BranchType branchType = 22;
- optional string errorType = 23;
- optional string pullRequest = 24;
- optional string pullRequestTitle = 25;
- optional int32 warningCount = 26;
- repeated string warnings = 27;
+ optional string branch = 20;
+ optional sonarqube.ws.commons.BranchType branchType = 21;
+ optional string errorType = 22;
+ optional string pullRequest = 23;
+ optional string pullRequestTitle = 24;
+ optional int32 warningCount = 25;
+ repeated string warnings = 26;
}
enum TaskStatus {