import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
-import org.sonar.api.config.internal.Settings;
import org.sonar.api.config.internal.ConfigurationBridge;
+import org.sonar.api.config.internal.Settings;
import org.sonar.db.DbClient;
-import org.sonar.db.component.BranchType;
import org.sonar.server.setting.ChildSettings;
-import static org.sonar.db.component.ComponentDto.generateBranchKey;
-import static org.sonar.db.component.ComponentDto.generatePullRequestKey;
-
@ComputeEngineSide
public class ProjectConfigurationFactory {
public Configuration newProjectConfiguration(String projectKey, Branch branch) {
Settings projectSettings = new ChildSettings(globalSettings);
addSettings(projectSettings, projectKey);
- if (branch.getType() == BranchType.PULL_REQUEST) {
- addSettings(projectSettings, generatePullRequestKey(projectKey, branch.getPullRequestKey()));
- } else {
- addSettings(projectSettings, generateBranchKey(projectKey, branch.getName()));
- }
+ // TODO branch / PR
+ addSettings(projectSettings, projectKey);
return new ConfigurationBridge(projectSettings);
}
underTest.execute(new TestComputationStepContext());
- assertThat(db.countRowsOfTable("components")).isEqualTo(3);
+ // 3 in this branch plus the project
+ assertThat(db.countRowsOfTable("components")).isEqualTo(4);
ComponentDto directoryDto = dbClient.componentDao().selectByKeyAndBranch(db.getSession(), "PROJECT_KEY:src/main/java/dir", "feature/foo").get();
assertThat(directoryDto.name()).isEqualTo("dir");
mapper(session).setPrivateForRootComponentUuid(branchUuid, isPrivate);
}
- public void setPrivateForRootComponentUuid(DbSession session, String branchUuid, boolean isPrivate,
- @Nullable String qualifier, String componentKey, String componentName) {
+ public void setPrivateForRootComponentUuid(DbSession session, String branchUuid, boolean isPrivate, @Nullable String qualifier, String componentKey, String componentName) {
ComponentNewValue componentNewValue = new ComponentNewValue(branchUuid, componentName, componentKey, isPrivate, qualifier);
auditPersister.updateComponentVisibility(session, componentNewValue);
mapper(session).setPrivateForRootComponentUuid(branchUuid, isPrivate);
* Example:
* - project P : kee=P, uuid=U1, qualifier=TRK, project_uuid=U1, main_branch_project_uuid=NULL
* - file F of project P : kee=P:F, uuid=U2, qualifier=FIL, project_uuid=U1, main_branch_project_uuid=NULL
- * - branch B of project P : kee=P:BRANCH:B, uuid=U3, qualifier=TRK, project_uuid=U3, main_branch_project_uuid=U1
- * - file F in branch B of project P : kee=P:F:BRANCH:B, uuid=U4, qualifier=FIL, project_uuid=U3, main_branch_project_uuid=U1
+ * - branch B of project P : kee=P, uuid=U3, qualifier=TRK, project_uuid=U3, main_branch_project_uuid=U1
+ * - file F in branch B of project P : kee=P:F, uuid=U4, qualifier=FIL, project_uuid=U3, main_branch_project_uuid=U1
*/
@Nullable
private String mainBranchProjectUuid;
return format("%s%s%s", componentKey, BRANCH_KEY_SEPARATOR, branch);
}
- public static String generatePullRequestKey(String componentKey, String pullRequest) {
- return format("%s%s%s", componentKey, PULL_REQUEST_SEPARATOR, pullRequest);
- }
-
public static String removeBranchAndPullRequestFromKey(String componentKey) {
return substringBeforeLast(substringBeforeLast(componentKey, ComponentDto.BRANCH_KEY_SEPARATOR), ComponentDto.PULL_REQUEST_SEPARATOR);
}
import com.google.common.annotations.VisibleForTesting;
import java.util.Collection;
import java.util.List;
-import java.util.Objects;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
}
public void updateApplicationBranchKey(DbSession dbSession, String appBranchUuid, String appKey, String newBranchName) {
+ // TODO review
ComponentKeyUpdaterMapper mapper = dbSession.getMapper(ComponentKeyUpdaterMapper.class);
String newAppBranchKey = generateBranchKey(appKey, newBranchName);
}
}
- public static final class RekeyedResource {
- private final ResourceDto resource;
- private final String oldKey;
-
- public RekeyedResource(ResourceDto resource, String oldKey) {
- this.resource = resource;
- this.oldKey = oldKey;
- }
-
- public ResourceDto getResource() {
- return resource;
- }
-
- public String getOldKey() {
- return oldKey;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- RekeyedResource that = (RekeyedResource) o;
- return Objects.equals(resource.getUuid(), that.resource.getUuid());
- }
-
- @Override
- public int hashCode() {
- return resource.getUuid().hashCode();
- }
- }
-
public static void checkExistentKey(ComponentKeyUpdaterMapper mapper, String resourceKey) {
- if (mapper.countResourceByKey(resourceKey) > 0) {
+ if (mapper.countComponentsByKey(resourceKey) > 0) {
throw new IllegalArgumentException("Impossible to update key: a component with key \"" + resourceKey + "\" already exists.");
}
}
public interface ComponentKeyUpdaterMapper {
- int countResourceByKey(String key);
+ int countComponentsByKey(String key);
ResourceDto selectProjectByUuid(@Param("uuid") String uuid);
List<ResourceDto> selectProjectResources(@Param("rootUuid") String rootUuid);
- List<ResourceDto> selectDescendantProjects(@Param("rootUuid") String rootUuid);
-
void updateComponent(ResourceDto resource);
void updateProject(@Param("oldProjectKey") String oldProjectKey, @Param("newProjectKey") String newProjectKey);
return session.getMapper(MeasureMapper.class);
}
- public List<ProjectMeasureDto> selectLastMeasureForAllProjects(DbSession session, String metricKey) {
- return mapper(session).selectLastMeasureForAllProjects(metricKey);
+ public List<ProjectMeasureDto> selectMeasureFromLargestBranchForAllProjects(DbSession session, String metricKey) {
+ return mapper(session).selectMeasureFromLargestBranchForAllProjects(metricKey);
}
}
void insert(MeasureDto measureDto);
- List<ProjectMeasureDto> selectLastMeasureForAllProjects(@Param("metricKey") String metricKey);
+ List<ProjectMeasureDto> selectMeasureFromLargestBranchForAllProjects(@Param("metricKey") String metricKey);
}
}
}
+ // TODO distinguish branch from project
public List<PropertyDto> selectProjectProperties(DbSession session, String projectKey) {
return getMapper(session).selectProjectProperties(projectKey);
}
<result property="enabled" column="enabled"/>
</resultMap>
- <select id="countResourceByKey" parameterType="String" resultType="int">
+ <select id="countComponentsByKey" parameterType="String" resultType="int">
SELECT count(1)
FROM components
WHERE kee = #{key,jdbcType=VARCHAR}
and scope != 'PRJ'
</select>
- <select id="selectDescendantProjects" parameterType="String" resultMap="resourceResultMap">
- select * from components
- where
- scope='PRJ'
- and root_uuid = #{rootUuid,jdbcType=VARCHAR}
- and uuid != #{rootUuid,jdbcType=VARCHAR}
- </select>
-
<update id="updateComponent" parameterType="Resource">
update components
set kee = #{key,jdbcType=VARCHAR}, deprecated_kee = #{deprecatedKey,jdbcType=VARCHAR}
from
(select counter.projectUuid as projectUuid,
counter.maxncloc ncloc,
- max(case
- when c.main_branch_project_uuid is null
- then 1
- else 0
- end) as mainBranch,
- min(c.kee) as component_kee,
+ min(br.uuid) as branchUuid,
counter.projectName,
counter.projectKey
from
group by b.project_uuid, p.name, p.kee) counter
inner join live_measures lmo on lmo.value = counter.maxncloc
inner join project_branches br on br.project_uuid = counter.projectUuid and br.uuid = lmo.component_uuid
- inner join components c on c.uuid = br.uuid
group by counter.projectUuid, counter.maxncloc, counter.projectName, counter.projectKey) tie_breaker
- inner join components c2 on c2.kee = tie_breaker.component_kee
- inner join project_branches pb on c2.uuid = pb.uuid
+ inner join project_branches pb on tie_breaker.branchUuid = pb.uuid
order by ncloc desc
</select>
+
<select id="countProjectsHavingMeasure" parameterType="map" resultType="long">
select count(1)
from live_measures lm
</select>
- <select id="selectLastMeasureForAllProjects" parameterType="map" resultType="ProjectMeasure">
+ <select id="selectMeasureFromLargestBranchForAllProjects" parameterType="map" resultType="ProjectMeasure">
select tie_breaker.projectUuid as projectUuid,
s.build_date as lastAnalysis,
ncloc as loc,
from
(select counter.projectUuid as projectUuid,
counter.maxncloc ncloc,
- max(case
- when c.main_branch_project_uuid is null
- then 1
- else 0
- end) as mainBranch,
- min(c.kee) as component_kee,
+ min(br.uuid) as branchUuid,
counter.projectName,
counter.projectKey
from
inner join project_branches br on br.project_uuid = counter.projectUuid and br.uuid = lmo.component_uuid
inner join components c on c.uuid = br.uuid
group by counter.projectUuid, counter.maxncloc, counter.projectName, counter.projectKey) tie_breaker
- inner join components c2 on c2.kee = tie_breaker.component_kee
- inner join project_branches pb on c2.uuid = pb.uuid
+ inner join project_branches pb on tie_breaker.branchUuid = pb.uuid
inner join project_measures pm on pb.uuid = pm.component_uuid
inner join snapshots s on s.component_uuid = pb.uuid and s.islast = ${_true}
inner join metrics m on m.name = #{metricKey,jdbcType=VARCHAR} and m.uuid = pm.metric_uuid
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditPersister;
import org.sonar.db.audit.model.ComponentKeyNewValue;
-import org.sonar.db.component.ComponentKeyUpdaterDao.RekeyedResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
public class ComponentKeyUpdaterDaoTest {
-
+
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
- private AuditPersister auditPersister = mock(AuditPersister.class);
- private DbClient dbClient = db.getDbClient();
- private DbSession dbSession = db.getSession();
- private ComponentKeyUpdaterDao underTest = db.getDbClient().componentKeyUpdaterDao();
- private ComponentKeyUpdaterDao underTestWithAuditPersister = new ComponentKeyUpdaterDao(auditPersister);
+ private final AuditPersister auditPersister = mock(AuditPersister.class);
+ private final DbClient dbClient = db.getDbClient();
+ private final DbSession dbSession = db.getSession();
+ private final ComponentKeyUpdaterDao underTest = db.getDbClient().componentKeyUpdaterDao();
+ private final ComponentKeyUpdaterDao underTestWithAuditPersister = new ComponentKeyUpdaterDao(auditPersister);
@Test
public void updateKey_changes_the_key_of_tree_of_components() {
@Test
public void updateKey_updates_branches_too() {
ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
+ String branchKey = RandomStringUtils.randomAlphanumeric(100);
+ ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey(branchKey));
db.components().insertComponent(newFileDto(branch));
db.components().insertComponent(newFileDto(branch));
- int branchComponentCount = 3;
+ int prComponentCount = 3;
String oldProjectKey = project.getKey();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).hasSize(1);
-
- String oldBranchKey = branch.getKey();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).hasSize(branchComponentCount);
+ assertThat(dbClient.componentDao().selectByBranchUuid(project.uuid(), dbSession)).hasSize(1);
+ assertThat(dbClient.componentDao().selectByBranchUuid(branch.uuid(), dbSession)).hasSize(prComponentCount);
String newProjectKey = "newKey";
- String newBranchKey = ComponentDto.generateBranchKey(newProjectKey, branch.getBranch());
underTest.updateKey(dbSession, project.uuid(), newProjectKey);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).isEmpty();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).isEmpty();
+ assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
+ assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
+ assertThat(dbClient.componentDao().selectByKeyAndBranch(dbSession, newProjectKey, branchKey)).isPresent();
+ assertThat(dbClient.componentDao().selectByBranchUuid(project.uuid(), dbSession)).hasSize(1);
+ assertThat(dbClient.componentDao().selectByBranchUuid(branch.uuid(), dbSession)).hasSize(prComponentCount);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, newProjectKey)).hasSize(1);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, newBranchKey)).hasSize(branchComponentCount);
db.select(dbSession, "select kee from components")
.forEach(map -> map.values().forEach(k -> assertThat(k.toString()).startsWith(newProjectKey)));
}
ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(PULL_REQUEST).setKey(pullRequestKey1));
db.components().insertComponent(newFileDto(pullRequest));
db.components().insertComponent(newFileDto(pullRequest));
- int branchComponentCount = 3;
+ int prComponentCount = 3;
String oldProjectKey = project.getKey();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).hasSize(1);
-
- String oldBranchKey = pullRequest.getKey();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).hasSize(branchComponentCount);
+ assertThat(dbClient.componentDao().selectByBranchUuid(project.uuid(), dbSession)).hasSize(1);
+ assertThat(dbClient.componentDao().selectByBranchUuid(pullRequest.uuid(), dbSession)).hasSize(prComponentCount);
String newProjectKey = "newKey";
- String newBranchKey = ComponentDto.generatePullRequestKey(newProjectKey, pullRequestKey1);
underTest.updateKey(dbSession, project.uuid(), newProjectKey);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldProjectKey)).isEmpty();
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, oldBranchKey)).isEmpty();
+ assertThat(dbClient.componentDao().selectByKey(dbSession, oldProjectKey)).isEmpty();
+ assertThat(dbClient.componentDao().selectByKey(dbSession, newProjectKey)).isPresent();
+ assertThat(dbClient.componentDao().selectByKeyAndPullRequest(dbSession, newProjectKey, pullRequestKey1)).isPresent();
+
+ assertThat(dbClient.componentDao().selectByBranchUuid(project.uuid(), dbSession)).hasSize(1);
+ assertThat(dbClient.componentDao().selectByBranchUuid(pullRequest.uuid(), dbSession)).hasSize(prComponentCount);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, newProjectKey)).hasSize(1);
- assertThat(dbClient.componentDao().selectAllComponentsFromProjectKey(dbSession, newBranchKey)).hasSize(branchComponentCount);
db.select(dbSession, "select kee from components")
.forEach(map -> map.values().forEach(k -> assertThat(k.toString()).startsWith(newProjectKey)));
}
- private ComponentDto prefixDbKeyWithKey(ComponentDto componentDto, String key) {
- return componentDto.setKey(key + ":" + componentDto.getKey());
- }
-
@Test
public void updateKey_throws_IAE_if_component_with_specified_key_does_not_exist() {
populateSomeData();
.componentKeyUpdate(any(DbSession.class), any(ComponentKeyNewValue.class), anyString());
}
-
- private Predicate<RekeyedResource> doNotReturnAnyRekeyedResource() {
- return a -> false;
- }
-
private void populateSomeData() {
ComponentDto project1 = db.components().insertPrivateProject(t -> t.setKey("org.struts:struts").setUuid("A"));
ComponentDto module1 = db.components().insertComponent(newModuleDto(project1).setKey("org.struts:struts-core").setUuid("B"));
.orElseThrow(() -> new IllegalStateException("Project has invalid configuration"));
}
+ public ComponentDto getComponentDto(ProjectDto project) {
+ return db.getDbClient().componentDao().selectByUuid(dbSession, project.getUuid())
+ .orElseThrow(() -> new IllegalStateException("Can't find project"));
+ }
+
+ public ComponentDto getComponentDto(BranchDto branch) {
+ return db.getDbClient().componentDao().selectByUuid(dbSession, branch.getUuid())
+ .orElseThrow(() -> new IllegalStateException("Can't find branch"));
+ }
+
public ComponentDto insertPrivateProject(ComponentDto componentDto) {
return insertComponentAndBranchAndProject(componentDto, true);
}
return getProjectDto(componentDto);
}
+ public final ComponentDto insertFile(ProjectDto project) {
+ ComponentDto projectComponent = getComponentDto(project);
+ return insertComponent(ComponentTesting.newFileDto(projectComponent));
+ }
+
+ public final ComponentDto insertFile(BranchDto branch) {
+ ComponentDto projectComponent = getComponentDto(branch);
+ return insertComponent(ComponentTesting.newFileDto(projectComponent));
+ }
+
public final ComponentDto insertPrivateProject(String uuid, Consumer<ComponentDto> dtoPopulator) {
return insertComponentAndBranchAndProject(ComponentTesting.newPrivateProjectDto(uuid), true, defaults(), dtoPopulator);
}
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
-import static org.sonar.db.component.BranchType.PULL_REQUEST;
-import static org.sonar.db.component.ComponentDto.BRANCH_KEY_SEPARATOR;
-import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent;
}
public static ComponentDto newBranchComponent(ProjectDto project, BranchDto branchDto) {
- String branchName = branchDto.getKey();
- String branchSeparator = branchDto.getBranchType() == PULL_REQUEST ? PULL_REQUEST_SEPARATOR : BRANCH_KEY_SEPARATOR;
String uuid = branchDto.getUuid();
return new ComponentDto()
.setUuid(uuid)
.setBranchUuid(uuid)
.setModuleUuidPath(UUID_PATH_SEPARATOR + uuid + UUID_PATH_SEPARATOR)
.setRootUuid(uuid)
- // name of the branch is not mandatory on the main branch
- .setKey(branchName != null ? project.getKey() + branchSeparator + branchName : project.getKey())
+ .setKey(project.getKey())
.setMainBranchProjectUuid(project.getUuid())
.setName(project.getName())
.setLongName(project.getName())
public static ComponentDto newBranchComponent(ComponentDto project, BranchDto branchDto) {
checkArgument(project.qualifier().equals(Qualifiers.PROJECT) || project.qualifier().equals(Qualifiers.APP));
checkArgument(project.getMainBranchProjectUuid() == null);
- String branchName = branchDto.getKey();
String uuid = branchDto.getUuid();
return new ComponentDto()
.setUuid(uuid)
@Test
public void return_configuration_with_global_settings_main_branch_settings_and_branch_settings() {
+ // TODO
String globalKey = randomAlphanumeric(3);
String globalValue = randomAlphanumeric(4);
String mainBranchDbKey = randomAlphanumeric(5);
* @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, ComponentDto mainComponentDto,
- BranchDto mainComponentBranchDto);
+ ComponentDto createBranchComponent(DbSession dbSession, ComponentKey componentKey, ComponentDto mainComponentDto, BranchDto mainComponentBranchDto);
}
ComponentDto branchComponent;
if (isMainBranch(componentKey, mainBranch)) {
branchComponent = mainBranchComponent;
+ } else if(componentKey.getBranchName().isPresent()) {
+ branchComponent = dbClient.componentDao().selectByKeyAndBranch(dbSession, componentKey.getKey(), componentKey.getBranchName().get())
+ .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch));
} else {
- branchComponent = dbClient.componentDao().selectByKey(dbSession, componentKey.getKey())
+ branchComponent = dbClient.componentDao().selectByKeyAndPullRequest(dbSession, componentKey.getKey(), componentKey.getPullRequestKey().get())
.orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch));
}
import org.sonarqube.ws.ProjectBranches.Branch;
import org.sonarqube.ws.ProjectBranches.ListWsResponse;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
tuple("feature/bar", BranchType.BRANCH));
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam("project", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_if_missing_project_parameter() {
assertThatThrownBy(() -> ws.newRequest().execute())
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import org.sonar.api.utils.System2;
import org.sonar.ce.queue.CeQueue;
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.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
@Test
public void submit_a_report_on_existing_branch() {
ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
+ ComponentDto branch = db.components().insertProjectBranch(project, b -> b.setKey("branch1"));
UserDto user = db.users().insertUser();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, project);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
- BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(branch);
- when(branchSupportDelegate.createComponentKey(project.getKey(), randomCharacteristics))
- .thenReturn(componentKey);
+ BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(project.getKey(), "branch1");
+ when(branchSupportDelegate.createComponentKey(project.getKey(), randomCharacteristics)).thenReturn(componentKey);
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
String taskUuid = mockSuccessfulPrepareSubmitCall();
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, existingProject);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
ComponentDto createdBranch = createButDoNotInsertBranch(existingProject);
- BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
- when(branchSupportDelegate.createComponentKey(existingProject.getKey(), randomCharacteristics))
- .thenReturn(componentKey);
- when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch)))
- .thenReturn(createdBranch);
+ BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(existingProject.getKey(), "branch1");
+ when(branchSupportDelegate.createComponentKey(existingProject.getKey(), randomCharacteristics)).thenReturn(componentKey);
+ 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();
verifyNoInteractions(favoriteUpdater);
verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(existingProject), eq(exitingProjectMainBranch));
verify(branchSupportDelegate).createComponentKey(existingProject.getKey(), randomCharacteristics);
- verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), 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);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
ComponentDto createdBranch = createButDoNotInsertBranch(nonExistingProject);
- BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
- when(branchSupportDelegate.createComponentKey(nonExistingProject.getKey(), randomCharacteristics))
- .thenReturn(componentKey);
+ BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(nonExistingProject.getKey());
+ when(branchSupportDelegate.createComponentKey(nonExistingProject.getKey(), randomCharacteristics)).thenReturn(componentKey);
when(componentUpdater.createWithoutCommit(any(), any(), eq(user.getUuid()), eq(user.getLogin()), any()))
.thenAnswer((Answer<ComponentDto>) invocation -> db.components().insertPrivateProject(nonExistingProject));
- 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);
+ 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);
BranchDto exitingProjectMainBranch = db.getDbClient().branchDao().selectByUuid(db.getSession(), nonExistingProject.uuid()).get();
verify(branchSupport).createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), eq(exitingProjectMainBranch));
verify(branchSupportDelegate).createComponentKey(nonExistingProject.getKey(), randomCharacteristics);
- verify(branchSupportDelegate).createBranchComponent(any(DbSession.class), same(componentKey), 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));
userSession.logIn(user).addProjectPermission(SCAN_EXECUTION, nonExistingProject);
Map<String, String> randomCharacteristics = randomNonEmptyMap();
ComponentDto createdBranch = createButDoNotInsertBranch(nonExistingProject);
- BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(createdBranch);
+ BranchSupport.ComponentKey componentKey = createComponentKeyOfBranch(nonExistingProject.getKey());
String nonExistingProjectDbKey = nonExistingProject.getKey();
- when(branchSupportDelegate.createComponentKey(nonExistingProjectDbKey, randomCharacteristics))
- .thenReturn(componentKey);
- when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any()))
- .thenReturn(createdBranch);
+ when(branchSupportDelegate.createComponentKey(nonExistingProjectDbKey, randomCharacteristics)).thenReturn(componentKey);
+ when(branchSupportDelegate.createBranchComponent(any(DbSession.class), same(componentKey), eq(nonExistingProject), any())).thenReturn(createdBranch);
InputStream reportInput = IOUtils.toInputStream("{binary}", StandardCharsets.UTF_8);
String name = nonExistingProject.name();
}
private void verifyQueueSubmit(ComponentDto project, ComponentDto branch, UserDto user, Map<String, String> characteristics, String taskUuid) {
- verify(queue).submit(argThat(submit -> submit.getType().equals(CeTaskTypes.REPORT)
- && submit.getComponent().filter(cpt -> cpt.getUuid().equals(branch.uuid()) && cpt.getMainComponentUuid().equals(project.uuid())).isPresent()
- && submit.getSubmitterUuid().equals(user.getUuid())
- && submit.getCharacteristics().equals(characteristics)
- && submit.getUuid().equals(taskUuid)));
+ ArgumentCaptor<CeTaskSubmit> captor = ArgumentCaptor.forClass(CeTaskSubmit.class);
+
+ verify(queue).submit(captor.capture());
+ CeTaskSubmit ceTask = captor.getValue();
+ assertThat(ceTask.getUuid()).isEqualTo(taskUuid);
+ assertThat(ceTask.getSubmitterUuid()).isEqualTo(user.getUuid());
+ assertThat(ceTask.getCharacteristics()).isEqualTo(characteristics);
+ assertThat(ceTask.getType()).isEqualTo(CeTaskTypes.REPORT);
+ assertThat(ceTask.getComponent()).isPresent();
+ assertThat(ceTask.getComponent().get().getUuid()).isEqualTo(branch.uuid());
+ assertThat(ceTask.getComponent().get().getMainComponentUuid()).isEqualTo(project.uuid());
}
- private static BranchSupport.ComponentKey createComponentKeyOfBranch(ComponentDto branch) {
- BranchSupport.ComponentKey componentKey = mockComponentKey(branch.getKey());
- when(componentKey.getBranchName()).thenReturn(Optional.of(branch).map(ComponentDto::name));
+ private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey) {
+ return createComponentKeyOfBranch(projectKey, randomAlphabetic(5));
+ }
+
+ private static BranchSupport.ComponentKey createComponentKeyOfBranch(String projectKey, String branchKey) {
+ BranchSupport.ComponentKey componentKey = mockComponentKey(projectKey);
+ when(componentKey.getBranchName()).thenReturn(Optional.of(branchKey));
return componentKey;
}
.hasMessage(format("Component id '%s' not found", branchUuid));
}
- @Test
- public void fail_to_getByUuidOrKey_when_using_branch_key() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- String branchDbKey = branch.getKey();
- assertThatThrownBy(() -> underTest.getByUuidOrKey(dbSession, null, branchDbKey, ID_AND_KEY))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_component_uuid_is_removed() {
ComponentDto project = db.components().insertComponent(newPrivateProjectDto());
.hasMessage("Component key 'file-key' not found");
}
- @Test
- public void fail_getByKey_on_branch() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- String branchDbKey = branch.getKey();
- assertThatThrownBy(() -> underTest.getByKey(dbSession, branchDbKey))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branchDbKey));
- }
-
@Test
public void get_component_by_uuid() {
db.components().insertComponent(newPrivateProjectDto("project-uuid"));
.hasMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- TestRequest request = ws.newRequest()
- .setParam(PARAM_COMPONENT, branch.getKey());
- assertThatThrownBy(() -> request.executeProtobuf(ShowWsResponse.class))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(String.format("Component key '%s' not found", branch.getKey()));
- }
-
private ShowWsResponse newRequest(@Nullable String key) {
TestRequest request = ws.newRequest();
if (key != null) {
tuple(file.getKey(), pullRequestId));
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- TestRequest request = ws.newRequest()
- .setParam(PARAM_COMPONENT, branch.getKey());
- assertThatThrownBy(() -> request.executeProtobuf(Components.ShowWsResponse.class))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_key() {
ComponentDto project = db.components().insertPrivateProject();
.hasMessage("The 'key' parameter is missing");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- TestRequest request = ws.newRequest()
- .setParam("key", branch.getKey());
-
- assertThatThrownBy(request::execute)
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
private TestRequest newBaseRequest() {
return ws.newRequest();
}
.isInstanceOf(UnauthorizedException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- UserDto user = db.users().insertUser();
- userSession.logIn(user).addProjectPermission(USER, project);
-
- assertThatThrownBy(() -> call(branch.getKey()))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_on_directory() {
ComponentDto project = db.components().insertPrivateProject();
.doesNotContain(branchIssue.getKey());
}
- @Test
- public void does_not_return_branch_issues_when_using_db_key() {
- RuleDto rule = db.rules().insertIssueRule();
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto projectFile = db.components().insertComponent(newFileDto(project));
- IssueDto projectIssue = db.issues().insertIssue(rule, project, projectFile);
- ComponentDto branch = db.components().insertProjectBranch(project);
- ComponentDto branchFile = db.components().insertComponent(newFileDto(branch));
- IssueDto branchIssue = db.issues().insertIssue(rule, branch, branchFile);
- allowAnyoneOnProjects(project);
- indexIssues();
-
- SearchWsResponse result = ws.newRequest()
- .setParam(PARAM_COMPONENT_KEYS, branch.getKey())
- .executeProtobuf(SearchWsResponse.class);
-
- assertThat(result.getIssuesList()).isEmpty();
- }
-
private void allowAnyoneOnProjects(ComponentDto... projects) {
userSession.registerComponents(projects);
Arrays.stream(projects).forEach(p -> permissionIndexer.allowOnlyAnyone(p));
import static org.sonar.api.utils.DateUtils.parseDate;
import static org.sonar.api.utils.DateUtils.parseDateTime;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
-import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.issue.IssueTesting.newDto;
import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection;
ComponentDto pr = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey("pr"));
SnapshotDto snapshotDto = db.components().insertSnapshot(pr);
indexPermissions();
- ComponentDto file = db.components().insertComponent(newFileDto(pr, null, "FILE_ID").setKey("FILE_KEY" + PULL_REQUEST_SEPARATOR + "pr"));
+ ComponentDto file = db.components().insertComponent(newFileDto(pr, null, "FILE_ID").setKey("FILE_KEY"));
RuleDto rule = newIssueRule();
IssueDto issue1 = newDto(rule, file, pr)
.setIssueCreationDate(parseDateTime("2014-09-04T00:00:00+0100"))
import org.sonarqube.ws.Measures.ComponentWsResponse;
import static java.lang.Double.parseDouble;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
.hasMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- MetricDto metric = db.measures().insertMetric(m -> m.setValueType("INT"));
-
- assertThatThrownBy(() -> {
- ws.newRequest()
- .setParam(PARAM_COMPONENT, branch.getKey())
- .setParam(PARAM_METRIC_KEYS, metric.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void json_example() {
ComponentDto project = db.components().insertPrivateProject();
.hasMessage(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- insertNclocMetric();
-
- assertThatThrownBy(() -> {
- ws.newRequest()
- .setParam(PARAM_COMPONENT, branch.getKey())
- .setParam(PARAM_METRIC_KEYS, "ncloc")
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
private static MetricDto newMetricDto() {
return MetricTesting.newMetricDto()
.setWorstValue(null)
import org.sonarqube.ws.Measures.SearchHistoryResponse.HistoryValue;
import static java.lang.Double.parseDouble;
-import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
.containsExactlyInAnyOrder(measure.getValue());
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam(PARAM_COMPONENT, branch.getKey())
- .setParam(PARAM_METRICS, "ncloc")
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_if_unknown_metric() {
SearchHistoryRequest request = SearchHistoryRequest.builder()
.setParam(PARAM_COMPONENT, "file-key")
.setParam(PARAM_METRICS, "ncloc")
.execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining("Component key 'file-key' not found");
+ .isInstanceOf(NotFoundException.class)
+ .hasMessageContaining("Component key 'file-key' not found");
}
@Test
.setParam(PARAM_BRANCH, "another_branch")
.setParam(PARAM_METRICS, "ncloc")
.execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
+ .isInstanceOf(NotFoundException.class)
+ .hasMessageContaining(String.format("Component '%s' on branch '%s' not found", file.getKey(), "another_branch"));
}
@Test
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
private Dispatchers dispatchers = mock(Dispatchers.class);
private WsActionTester ws = new WsActionTester(new AddAction(new NotificationCenter(
- new NotificationDispatcherMetadata[]{},
- new NotificationChannel[]{emailChannel, twitterChannel, defaultChannel}),
+ new NotificationDispatcherMetadata[] {},
+ new NotificationChannel[] {emailChannel, twitterChannel, defaultChannel}),
new NotificationUpdater(dbClient), dispatchers, dbClient, TestComponentFinder.from(db), userSession));
@Test
.isInstanceOf(UnauthorizedException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- UserDto user = db.users().insertUser();
- userSession.logIn(user);
- when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES));
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> call(NOTIF_MY_NEW_ISSUES, null, branch.getKey(), null))
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_user_does_not_have_USER_permission_on_private_project() {
ComponentDto project = db.components().insertPrivateProject();
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
.isInstanceOf(UnauthorizedException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- UserDto user = db.users().insertUser();
- userSession.logIn(user);
- when(dispatchers.getGlobalDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES));
- when(dispatchers.getProjectDispatchers()).thenReturn(singletonList(NOTIF_MY_NEW_ISSUES));
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- RemoveRequest request = this.request.setProject(branch.getKey());
- assertThatThrownBy(() -> call(request))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
private TestResponse call(RemoveRequest remove) {
TestRequest request = ws.newRequest();
request.setParam(PARAM_TYPE, remove.getType());
GroupDto group = db.users().insertGroup("sonar-administrators");
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PROJECT_ID, "not-found")
GroupDto group = db.users().insertGroup("sonar-administrators");
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PROJECT_ID, file.uuid())
GroupDto group = db.users().insertGroup("sonar-administrators");
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
executeRequest(group, UserRole.ISSUE_ADMIN);
})
.isInstanceOf(BadRequestException.class);
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project, null, "file-uuid"));
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PROJECT_ID, file.uuid())
public void fail_when_get_request() {
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setMethod("GET")
.setParam(PARAM_GROUP_NAME, "sonar-administrators")
public void fail_when_group_name_and_group_id_are_missing() {
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
.execute();
GroupDto group = db.users().insertGroup("sonar-administrators");
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
GroupDto group = db.users().insertGroup();
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.execute();
ComponentDto project = db.components().insertPrivateProject();
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
GroupDto group = db.users().insertGroup("sonar-administrators");
userSession.logIn().addPermission(SCAN);
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey())
ComponentDto project = db.components().insertPrivateProject();
userSession.logIn();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PERMISSION, PROVISION_PROJECTS.getKey())
assertThat(db.users().selectAnyonePermissions(project)).isEmpty();
}
- @Test
- public void fail_when_using_branch_db_key() {
- GroupDto group = db.users().insertGroup();
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_GROUP_NAME, group.getName())
- .setParam(PARAM_PERMISSION, ISSUE_ADMIN)
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
GroupDto group = db.users().insertGroup();
userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
ComponentDto branch = db.components().insertProjectBranch(project);
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_PROJECT_ID, branch.uuid())
.setParam(PARAM_GROUP_NAME, group.getName())
assertThat(db.users().selectAnyonePermissions(project)).isEmpty();
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_USER_LOGIN, user.getLogin())
- .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
ComponentDto project = db.components().insertPublicProject();
.isInstanceOf(NotFoundException.class)
.hasMessage(format("Project id '%s' not found", branch.uuid()));
}
-
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- GroupDto group = db.users().insertGroup();
- db.users().insertProjectPermissionOnGroup(group, ISSUE_ADMIN, project);
- loginAsAdmin();
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PERMISSION, ISSUE_ADMIN)
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
}
db.users().insertPermissionOnGroup(aGroup, PROVISION_PROJECTS);
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
executeRequest(aGroup, SYSTEM_ADMIN);
})
.isInstanceOf(BadRequestException.class)
public void fail_when_project_does_not_exist() {
loginAsAdmin();
- assertThatThrownBy(() -> {
+ assertThatThrownBy(() -> {
newRequest()
.setParam(PARAM_GROUP_NAME, aGroup.getName())
.setParam(PARAM_PROJECT_ID, "unknown-project-uuid")
.hasMessage("Permission codeviewer can't be removed from a public component");
}
- @Test
- public void fail_when_using_branch_db_key() {
- GroupDto group = db.users().insertGroup();
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_GROUP_NAME, group.getName())
- .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
GroupDto group = db.users().insertGroup();
.hasMessage("Permission codeviewer can't be removed from a public component");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_USER_LOGIN, user.getLogin())
- .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
ComponentDto project = db.components().insertPublicProject();
.hasMessage("'q' length (2) is shorter than the minimum authorized (3)");
}
- @Test
- public void fail_when_using_branch_db_key() throws Exception {
- UserDto user = db.users().insertUser(newUserDto());
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- db.users().insertProjectPermissionOnUser(user, ISSUE_ADMIN, project);
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
-
- assertThatThrownBy(() -> {
- newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_USER_LOGIN, user.getLogin())
- .setParam(PARAM_PERMISSION, SYSTEM_ADMIN)
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
UserDto user = db.users().insertUser(newUserDto());
.isInstanceOf(UnauthorizedException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- TestRequest request = tester.newRequest().setParam(PARAM_PROJECT, branch.getKey());
- assertThatThrownBy(() -> call(request))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(String.format("Project '%s' not found", branch.getKey()));
- }
-
private String verifyDeletedKey() {
ArgumentCaptor<ProjectDto> argument = ArgumentCaptor.forClass(ProjectDto.class);
verify(componentCleanerService).delete(any(DbSession.class), argument.capture());
.isInstanceOf(NotFoundException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- userSessionRule.addProjectPermission(UserRole.ADMIN, project);
-
- String branchDbKey = branch.getKey();
- assertThatThrownBy(() -> call(branchDbKey, ANOTHER_KEY))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(String.format("Project '%s' not found", branchDbKey));
- }
-
@Test
public void api_definition() {
WebService.Action definition = ws.getDef();
.hasMessage("Insufficient privileges");
}
-
@Test
public void execute_throws_ForbiddenException_if_user_has_ADMIN_permission_but_sonar_allowPermissionManagementForProjectAdmins_is_set_to_false() {
when(configuration.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)).thenReturn(of(false));
.containsOnly(UserRole.ADMIN);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = dbTester.components().insertPrivateProject();
- userSessionRule.logIn().addProjectPermission(UserRole.USER, project);
- ComponentDto branch = dbTester.components().insertProjectBranch(project);
-
- TestRequest request = this.request.setParam(PARAM_PROJECT, branch.getKey())
- .setParam(PARAM_VISIBILITY, PUBLIC);
- assertThatThrownBy(request::execute)
- .isInstanceOf(NotFoundException.class)
- .hasMessage(String.format("Component key '%s' not found", branch.getKey()));
- }
-
private void unsafeGiveAllPermissionsToRootComponent(ComponentDto component, UserDto user, GroupDto group) {
Arrays.stream(GlobalPermission.values())
.forEach(globalPermission -> {
import org.sonar.server.ce.projectdump.ExportSubmitter;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
assertJson(response.getInput()).isSimilarTo(responseExample());
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
-
- assertThatThrownBy(() -> {
- actionTester.newRequest()
- .setMethod("POST")
- .setParam("key", branch.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class);
- }
-
private void logInAsProjectAdministrator(String login) {
userSession.logIn(login).addProjectPermission(UserRole.ADMIN, project);
}
private final static String projectDumpsDirectoryPathname = "data/governance/project_dumps/";
private final static String importDirectoryPathname = Paths.get(projectDumpsDirectoryPathname, "import").toString();
- private final static String exportDirectoryPathname = Paths.get(projectDumpsDirectoryPathname,"export").toString();
+ private final static String exportDirectoryPathname = Paths.get(projectDumpsDirectoryPathname, "export").toString();
private ProjectDto project;
.doesNotContain("dumpToImport");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- underTest.newRequest()
- .setParam(KEY_PARAM, branch.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class);
- }
-
@Test
public void fail_when_using_branch_id() {
ComponentDto project = db.components().insertPublicProject();
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .setParam(PARAM_NAME, "Custom")
- .setParam(PARAM_URL, "http://example.org")
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_db_uuid() {
ComponentDto project = db.components().insertPrivateProject();
.isInstanceOf(IllegalArgumentException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_db_uuid() {
ComponentDto project = db.components().insertPrivateProject();
.hasMessage("Project 'FILE_KEY' not found");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- String branchDbKey = branch.getKey();
- assertThatThrownBy(() -> call(branchDbKey, "secret"))
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project '%s' not found", branchDbKey));
- }
-
@Test
public void definition() {
WebService.Action definition = ws.getDef();
.isInstanceOf(ForbiddenException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam("projectKey", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
@Test
public void definition() {
WebService.Action def = ws.getDef();
.hasMessageContaining("The 'project' parameter is missing");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest().setParam("project", branch.getKey()).execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
private void logInAsProjectUser(ProjectDto project) {
userSession.logIn().addProjectPermission(UserRole.USER, project);
}
.hasMessageContaining("Either 'analysisId', 'projectId' or 'projectKey' must be provided");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- SnapshotDto snapshot = db.components().insertSnapshot(branch);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam(PARAM_PROJECT_KEY, branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
ComponentDto project = db.components().insertPublicProject();
.isInstanceOf(ForbiddenException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- QualityGateDto qualityGate = db.qualityGates().insertQualityGate();
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> ws.newRequest()
- .setParam("gateId", qualityGate.getUuid())
- .setParam("projectKey", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Project '%s' not found", branch.getKey()));
- }
-
private void assertSelected(QualityGateDto qualityGate, ComponentDto project) {
Optional<String> qGateUuid = db.qualityGates().selectQGateUuidByComponentUuid(project.uuid());
assertThat(qGateUuid)
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn(db.users().insertUser()).addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- QProfileDto profile = db.qualityProfiles().insert();
-
- assertThatThrownBy(() -> {
- tester.newRequest()
- .setParam("project", branch.getKey())
- .setParam("profileKey", profile.getKee())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project '%s' not found", branch.getKey()));
- }
-
private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
.hasMessage("Quality Profile for language 'xoo' and name 'unknown' does not exist");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- QProfileDto profile = db.qualityProfiles().insert();
-
- assertThatThrownBy(() -> {
- ws.newRequest()
- .setParam("project", branch.getKey())
- .setParam("language", profile.getLanguage())
- .setParam("qualityProfile", profile.getName())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Project '%s' not found", branch.getKey()));
- }
-
private void assertProjectIsAssociatedToProfile(ProjectDto project, QProfileDto profile) {
QProfileDto loaded = dbClient.qualityProfileDao().selectAssociatedToProjectAndLanguage(db.getSession(), project, profile.getLanguage());
assertThat(loaded.getKee()).isEqualTo(profile.getKee());
failForPropertyWithoutDefinitionOnUnsupportedComponent(view, projectCopy);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
- definitions.addComponent(PropertyDefinition.builder("foo").onQualifiers(PROJECT).build());
-
- assertThatThrownBy(() -> {
- ws.newRequest()
- .setParam("keys", "foo")
- .setParam("component", branch.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_component_not_found() {
assertThatThrownBy(() -> {
.hasMessage("Setting 'my.key' cannot be set on a Project");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPublicProject();
- userSession.logIn().addProjectPermission(UserRole.ADMIN, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- callForProjectSettingByKey("my.key", "My Value", branch.getKey());
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_component_not_found() {
assertThatThrownBy(() -> {
JsonAssert.assertJson(newTester().getDef().responseExampleAsString()).isSimilarTo(result);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- userSession.logIn().addProjectPermission(UserRole.USER, project);
- ComponentDto branch = db.components().insertProjectBranch(project);
-
- assertThatThrownBy(() -> {
- newTester().newRequest()
- .setParam("keys", "foo")
- .setParam("component", branch.getKey())
- .execute();
- })
- .isInstanceOf(NotFoundException.class)
- .hasMessage(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_setting_key_is_defined_in_sonar_properties() {
ComponentDto project = db.components().insertPrivateProject();
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.USER;
.isInstanceOf(NotFoundException.class);
}
- @Test
- public void fail_when_using_branch_db_key() throws Exception {
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- userSession.addProjectPermission(USER, project);
-
- assertThatThrownBy(() -> tester.newRequest()
- .setParam("resource", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Component key '%s' not found", branch.getKey()));
- }
-
private static DbFileSources.Data newData(String... lines) {
DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder();
for (int i = 1; i <= lines.length; i++) {
.hasMessageContaining("Parameter 'uuid' cannot be used at the same time as 'branch' or 'pullRequest'");
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = db.components().insertPrivateProject();
- ComponentDto branch = db.components().insertProjectBranch(project);
- userSession.addProjectPermission(UserRole.USER, project);
-
- assertThatThrownBy(() -> tester.newRequest()
- .setParam("key", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Component key '%s' not found", branch.getKey()));
- }
-
@Test
public void fail_when_using_branch_uuid() {
ComponentDto project = db.components().insertPrivateProject();
import org.sonar.db.source.FileSourceDto;
import org.sonar.server.component.TestComponentFinder;
import org.sonar.server.exceptions.ForbiddenException;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.WsActionTester;
-import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ScmActionTest {
.isInstanceOf(ForbiddenException.class);
}
- @Test
- public void fail_when_using_branch_db_key() {
- ComponentDto project = dbTester.components().insertPrivateProject();
- ComponentDto branch = dbTester.components().insertProjectBranch(project);
- userSessionRule.addProjectPermission(UserRole.CODEVIEWER, project);
-
- assertThatThrownBy(() -> tester.newRequest()
- .setParam("key", branch.getKey())
- .execute())
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining(format("Component key '%s' not found", branch.getKey()));
- }
-
private DbFileSources.Line newSourceLine(String author, String revision, Date date, int line) {
return DbFileSources.Line.newBuilder()
.setScmAuthor(author)