3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.almintegration.ws.bitbucketserver;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.stream.Collectors;
27 import org.junit.Before;
28 import org.junit.BeforeClass;
29 import org.junit.Rule;
30 import org.junit.Test;
31 import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient;
32 import org.sonar.alm.client.bitbucketserver.Branch;
33 import org.sonar.alm.client.bitbucketserver.BranchesList;
34 import org.sonar.alm.client.bitbucketserver.Project;
35 import org.sonar.alm.client.bitbucketserver.Repository;
36 import org.sonar.api.server.ws.WebService;
37 import org.sonar.api.utils.System2;
38 import org.sonar.core.util.SequenceUuidFactory;
39 import org.sonar.db.DbTester;
40 import org.sonar.db.alm.pat.AlmPatDto;
41 import org.sonar.db.alm.setting.AlmSettingDto;
42 import org.sonar.db.component.BranchDto;
43 import org.sonar.db.project.ProjectDto;
44 import org.sonar.db.user.UserDto;
45 import org.sonar.server.almintegration.ws.ImportHelper;
46 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
47 import org.sonar.server.component.ComponentUpdater;
48 import org.sonar.server.es.TestProjectIndexers;
49 import org.sonar.server.exceptions.BadRequestException;
50 import org.sonar.server.exceptions.ForbiddenException;
51 import org.sonar.server.exceptions.NotFoundException;
52 import org.sonar.server.exceptions.UnauthorizedException;
53 import org.sonar.server.favorite.FavoriteUpdater;
54 import org.sonar.server.l18n.I18nRule;
55 import org.sonar.server.permission.PermissionTemplateService;
56 import org.sonar.server.project.ProjectDefaultVisibility;
57 import org.sonar.server.project.Visibility;
58 import org.sonar.server.tester.UserSessionRule;
59 import org.sonar.server.ws.WsActionTester;
60 import org.sonarqube.ws.Projects;
62 import static java.util.Objects.requireNonNull;
63 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
64 import static org.apache.commons.lang.math.JVMRandom.nextLong;
65 import static org.assertj.core.api.Assertions.assertThat;
66 import static org.assertj.core.api.Assertions.assertThatThrownBy;
67 import static org.assertj.core.api.Assertions.tuple;
68 import static org.mockito.ArgumentMatchers.any;
69 import static org.mockito.Mockito.mock;
70 import static org.mockito.Mockito.verify;
71 import static org.mockito.Mockito.when;
72 import static org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto;
73 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
74 import static org.sonar.db.permission.GlobalPermission.SCAN;
76 public class ImportBitbucketServerProjectActionTest {
77 private static final String GENERATED_PROJECT_KEY = "TEST_PROJECT_KEY";
80 public UserSessionRule userSession = UserSessionRule.standalone();
82 public DbTester db = DbTester.create();
84 public final I18nRule i18n = new I18nRule();
86 private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
87 private final BitbucketServerRestClient bitbucketServerRestClient = mock(BitbucketServerRestClient.class);
89 private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), i18n, System2.INSTANCE,
90 mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory());
92 private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
93 private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
94 private final WsActionTester ws = new WsActionTester(new ImportBitbucketServerProjectAction(db.getDbClient(), userSession,
95 bitbucketServerRestClient, projectDefaultVisibility, componentUpdater, importHelper, projectKeyGenerator));
97 private static BranchesList defaultBranchesList;
100 public static void beforeAll() {
101 Branch defaultBranch = new Branch("default", true);
102 defaultBranchesList = new BranchesList(Collections.singletonList(defaultBranch));
106 public void before() {
107 when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
108 when(projectKeyGenerator.generateUniqueProjectKey(any(), any())).thenReturn(GENERATED_PROJECT_KEY);
112 public void import_project() {
113 UserDto user = db.users().insertUser();
114 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
115 AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
116 db.almPats().insert(dto -> {
117 dto.setAlmSettingUuid(almSetting.getUuid());
118 dto.setUserUuid(user.getUuid());
120 Project project = getGsonBBSProject();
121 Repository repo = getGsonBBSRepo(project);
122 when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
123 when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList);
125 Projects.CreateWsResponse response = ws.newRequest()
126 .setParam("almSetting", almSetting.getKey())
127 .setParam("projectKey", "projectKey")
128 .setParam("repositorySlug", "repo-slug")
129 .executeProtobuf(Projects.CreateWsResponse.class);
131 Projects.CreateWsResponse.Project result = response.getProject();
132 assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
133 assertThat(result.getName()).isEqualTo(repo.getName());
135 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
136 assertThat(projectDto).isPresent();
137 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
138 verify(projectKeyGenerator).generateUniqueProjectKey(requireNonNull(project.getKey()), repo.getSlug());
142 public void fail_project_already_exist() {
143 UserDto user = db.users().insertUser();
144 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
145 AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
146 db.almPats().insert(dto -> {
147 dto.setAlmSettingUuid(almSetting.getUuid());
148 dto.setUserUuid(user.getUuid());
150 Project project = getGsonBBSProject();
151 Repository repo = getGsonBBSRepo(project);
152 db.components().insertPublicProject(p -> p.setDbKey(GENERATED_PROJECT_KEY));
154 assertThatThrownBy(() -> {
155 when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
156 when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(defaultBranchesList);
159 .setParam("almSetting", almSetting.getKey())
160 .setParam("projectKey", "projectKey")
161 .setParam("repositorySlug", "repo-slug")
164 .isInstanceOf(BadRequestException.class)
165 .hasMessage("Could not create Project with key: \"%s\". A similar key already exists: \"%s\"", GENERATED_PROJECT_KEY, GENERATED_PROJECT_KEY);
169 public void fail_when_not_logged_in() {
170 assertThatThrownBy(() -> {
172 .setParam("almSetting", "sdgfdshfjztutz")
173 .setParam("projectKey", "projectKey")
174 .setParam("repositorySlug", "repo-slug")
177 .isInstanceOf(UnauthorizedException.class);
181 public void fail_when_missing_project_creator_permission() {
182 UserDto user = db.users().insertUser();
183 userSession.logIn(user).addPermission(SCAN);
185 assertThatThrownBy(() -> {
187 .setParam("almSetting", "sdgfdshfjztutz")
188 .setParam("projectKey", "projectKey")
189 .setParam("repositorySlug", "repo-slug")
192 .isInstanceOf(ForbiddenException.class)
193 .hasMessage("Insufficient privileges");
197 public void check_pat_is_missing() {
198 UserDto user = db.users().insertUser();
199 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
200 AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
202 assertThatThrownBy(() -> {
204 .setParam("almSetting", almSetting.getKey())
207 .isInstanceOf(IllegalArgumentException.class)
208 .hasMessage("personal access token for '" + almSetting.getKey() + "' is missing");
212 public void fail_check_alm_setting_not_found() {
213 UserDto user = db.users().insertUser();
214 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
215 AlmPatDto almPatDto = newAlmPatDto();
216 db.getDbClient().almPatDao().insert(db.getSession(), almPatDto, user.getLogin(), null);
218 assertThatThrownBy(() -> {
220 .setParam("almSetting", "testKey")
223 .isInstanceOf(NotFoundException.class)
224 .hasMessage("ALM Setting 'testKey' not found");
228 public void fail_when_no_creation_project_permission() {
229 UserDto user = db.users().insertUser();
230 userSession.logIn(user);
232 assertThatThrownBy(() -> {
234 .setParam("almSetting", "anyvalue")
237 .isInstanceOf(ForbiddenException.class)
238 .hasMessage("Insufficient privileges");
242 public void handle_givenNoDefaultBranchFound_doNotUpdateDefaultBranchName() {
243 BranchesList branchesList = new BranchesList();
244 Branch branch = new Branch("not_a_master", false);
245 branchesList.addBranch(branch);
247 UserDto user = db.users().insertUser();
248 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
249 AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
250 db.almPats().insert(dto -> {
251 dto.setAlmSettingUuid(almSetting.getUuid());
252 dto.setUserUuid(user.getUuid());
254 Project project = getGsonBBSProject();
255 Repository repo = getGsonBBSRepo(project);
256 when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
257 when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList);
259 Projects.CreateWsResponse response = ws.newRequest()
260 .setParam("almSetting", almSetting.getKey())
261 .setParam("projectKey", "projectKey")
262 .setParam("repositorySlug", "repo-slug")
263 .executeProtobuf(Projects.CreateWsResponse.class);
265 Projects.CreateWsResponse.Project result = response.getProject();
267 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
269 Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get());
270 List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).collect(Collectors.toList());
271 String mainBranchName = collect.iterator().next().getKey();
272 assertThat(mainBranchName).isEqualTo("master");
276 public void handle_givenDefaultBranchNamedDefault_updateDefaultBranchNameToDefault() {
277 BranchesList branchesList = new BranchesList();
278 Branch branch = new Branch("default", true);
279 branchesList.addBranch(branch);
281 UserDto user = db.users().insertUser();
282 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
283 AlmSettingDto almSetting = db.almSettings().insertGitHubAlmSetting();
284 db.almPats().insert(dto -> {
285 dto.setAlmSettingUuid(almSetting.getUuid());
286 dto.setUserUuid(user.getUuid());
288 Project project = getGsonBBSProject();
289 Repository repo = getGsonBBSRepo(project);
290 when(bitbucketServerRestClient.getRepo(any(), any(), any(), any())).thenReturn(repo);
291 when(bitbucketServerRestClient.getBranches(any(), any(), any(), any())).thenReturn(branchesList);
293 Projects.CreateWsResponse response = ws.newRequest()
294 .setParam("almSetting", almSetting.getKey())
295 .setParam("projectKey", "projectKey")
296 .setParam("repositorySlug", "repo-slug")
297 .executeProtobuf(Projects.CreateWsResponse.class);
299 Projects.CreateWsResponse.Project result = response.getProject();
301 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
303 Collection<BranchDto> branchDtos = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get());
304 List<BranchDto> collect = branchDtos.stream().filter(BranchDto::isMain).collect(Collectors.toList());
305 String mainBranchName = collect.iterator().next().getKey();
306 assertThat(mainBranchName).isEqualTo("default");
310 public void definition() {
311 WebService.Action def = ws.getDef();
313 assertThat(def.since()).isEqualTo("8.2");
314 assertThat(def.isPost()).isTrue();
315 assertThat(def.params())
316 .extracting(WebService.Param::key, WebService.Param::isRequired)
317 .containsExactlyInAnyOrder(
318 tuple("almSetting", true),
319 tuple("repositorySlug", true),
320 tuple("projectKey", true));
323 private Repository getGsonBBSRepo(Project project) {
324 Repository bbsResult = new Repository();
325 bbsResult.setProject(project);
326 bbsResult.setSlug(randomAlphanumeric(5));
327 bbsResult.setName(randomAlphanumeric(5));
328 bbsResult.setId(nextLong(100));
332 private Project getGsonBBSProject() {
334 .setKey(randomAlphanumeric(5))
335 .setId(nextLong(100))
336 .setName(randomAlphanumeric(5));