3 * Copyright (C) 2009-2023 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.gitlab;
22 import java.util.List;
23 import java.util.Optional;
24 import org.assertj.core.api.Assertions;
25 import org.junit.Before;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.sonar.alm.client.gitlab.GitLabBranch;
29 import org.sonar.alm.client.gitlab.GitlabHttpClient;
30 import org.sonar.alm.client.gitlab.Project;
31 import org.sonar.api.utils.System2;
32 import org.sonar.core.i18n.I18n;
33 import org.sonar.core.platform.EditionProvider;
34 import org.sonar.core.platform.PlatformEditionProvider;
35 import org.sonar.core.util.SequenceUuidFactory;
36 import org.sonar.db.DbTester;
37 import org.sonar.db.alm.setting.AlmSettingDto;
38 import org.sonar.db.component.BranchDto;
39 import org.sonar.db.newcodeperiod.NewCodePeriodDto;
40 import org.sonar.db.project.CreationMethod;
41 import org.sonar.db.project.ProjectDto;
42 import org.sonar.db.user.UserDto;
43 import org.sonar.server.almintegration.ws.ImportHelper;
44 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
45 import org.sonar.server.component.ComponentUpdater;
46 import org.sonar.server.es.TestIndexers;
47 import org.sonar.server.favorite.FavoriteUpdater;
48 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
49 import org.sonar.server.permission.PermissionService;
50 import org.sonar.server.permission.PermissionTemplateService;
51 import org.sonar.server.permission.PermissionUpdater;
52 import org.sonar.server.project.DefaultBranchNameResolver;
53 import org.sonar.server.project.ProjectDefaultVisibility;
54 import org.sonar.server.project.Visibility;
55 import org.sonar.server.tester.UserSessionRule;
56 import org.sonar.server.ws.WsActionTester;
57 import org.sonarqube.ws.Projects;
59 import static java.util.Collections.emptyList;
60 import static java.util.Collections.singletonList;
61 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
62 import static org.assertj.core.api.Assertions.assertThat;
63 import static org.assertj.core.api.Assertions.tuple;
64 import static org.mockito.ArgumentMatchers.any;
65 import static org.mockito.Mockito.mock;
66 import static org.mockito.Mockito.verify;
67 import static org.mockito.Mockito.when;
68 import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
69 import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
70 import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
71 import static org.sonar.server.tester.UserSessionRule.standalone;
72 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
73 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
75 public class ImportGitLabProjectActionIT {
77 private static final String PROJECT_KEY_NAME = "PROJECT_NAME";
79 private final System2 system2 = mock(System2.class);
82 public UserSessionRule userSession = standalone();
85 public DbTester db = DbTester.create(system2);
87 DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class);
89 private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
90 mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(),
91 defaultBranchNameResolver, mock(PermissionUpdater.class), mock(PermissionService.class));
93 private final GitlabHttpClient gitlabHttpClient = mock(GitlabHttpClient.class);
94 private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
95 private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
96 private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
97 private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
98 private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider);
99 private final ImportGitLabProjectAction importGitLabProjectAction = new ImportGitLabProjectAction(
100 db.getDbClient(), userSession, projectDefaultVisibility, gitlabHttpClient, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver,
101 defaultBranchNameResolver);
102 private final WsActionTester ws = new WsActionTester(importGitLabProjectAction);
105 public void before() {
106 when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
107 when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME);
111 public void import_project_developer_edition() {
112 when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
114 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
115 Project project = mockGitlabProject(singletonList(new GitLabBranch("master", true)));
117 Projects.CreateWsResponse response = ws.newRequest()
118 .setParam("almSetting", almSetting.getKey())
119 .setParam("gitlabProjectId", "12345")
120 .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
121 .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
122 .executeProtobuf(Projects.CreateWsResponse.class);
124 verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
126 Projects.CreateWsResponse.Project result = response.getProject();
127 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
128 assertThat(result.getName()).isEqualTo(project.getName());
130 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
131 assertThat(projectDto).isPresent();
132 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
134 assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid()))
137 .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
138 .containsExactly(NUMBER_OF_DAYS, "30", null);
142 public void import_project_community_edition() {
143 when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
145 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
146 mockGitlabProject(singletonList(new GitLabBranch("master", true)));
148 Projects.CreateWsResponse response = ws.newRequest()
149 .setParam("almSetting", almSetting.getKey())
150 .setParam("gitlabProjectId", "12345")
151 .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
152 .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
153 .executeProtobuf(Projects.CreateWsResponse.class);
155 Projects.CreateWsResponse.Project result = response.getProject();
157 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
158 BranchDto branchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(db.getSession(), projectDto.get().getUuid()).orElseThrow();
160 String projectUuid = projectDto.get().getUuid();
161 assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, branchDto.getUuid()))
164 .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
165 .containsExactly(NUMBER_OF_DAYS, "30", branchDto.getUuid());
169 public void import_project_with_specific_different_default_branch() {
170 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
171 Project project = mockGitlabProject(singletonList(new GitLabBranch("main", true)));
173 Projects.CreateWsResponse response = ws.newRequest()
174 .setParam("almSetting", almSetting.getKey())
175 .setParam("gitlabProjectId", "12345")
176 .executeProtobuf(Projects.CreateWsResponse.class);
178 verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
179 verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L);
181 Projects.CreateWsResponse.Project result = response.getProject();
182 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
183 assertThat(result.getName()).isEqualTo(project.getName());
185 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
186 assertThat(projectDto).isPresent();
187 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
189 Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()))
190 .extracting(BranchDto::getKey, BranchDto::isMain)
191 .containsExactlyInAnyOrder(tuple("main", true));
195 public void import_project_no_gitlab_default_branch() {
196 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
197 Project project = mockGitlabProject(emptyList());
199 Projects.CreateWsResponse response = ws.newRequest()
200 .setParam("almSetting", almSetting.getKey())
201 .setParam("gitlabProjectId", "12345")
202 .executeProtobuf(Projects.CreateWsResponse.class);
204 verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
205 verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L);
207 Projects.CreateWsResponse.Project result = response.getProject();
208 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
209 assertThat(result.getName()).isEqualTo(project.getName());
211 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
212 assertThat(projectDto).isPresent();
213 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
215 Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()))
216 .extracting(BranchDto::getKey, BranchDto::isMain)
217 .containsExactlyInAnyOrder(tuple(DEFAULT_MAIN_BRANCH_NAME, true));
221 public void import_project_without_NCD() {
222 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
223 Project project = mockGitlabProject(singletonList(new GitLabBranch("master", true)));
225 Projects.CreateWsResponse response = ws.newRequest()
226 .setParam("almSetting", almSetting.getKey())
227 .setParam("gitlabProjectId", "12345")
228 .executeProtobuf(Projects.CreateWsResponse.class);
230 verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
232 Projects.CreateWsResponse.Project result = response.getProject();
233 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
234 assertThat(result.getName()).isEqualTo(project.getName());
236 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
237 assertThat(projectDto).isPresent();
238 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
242 public void importProject_whenNonBrowserCall_setsCreationMethodToApi() {
243 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
244 mockGitlabProject(singletonList(new GitLabBranch("master", true)));
246 Projects.CreateWsResponse response = ws.newRequest()
247 .setParam("almSetting", almSetting.getKey())
248 .setParam("gitlabProjectId", "12345")
249 .executeProtobuf(Projects.CreateWsResponse.class);
251 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
252 assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_API);
256 public void importProject_whenBrowserCall_setsCreationMethodToBrowser() {
257 AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
258 userSession.flagSessionAsGui();
259 mockGitlabProject(singletonList(new GitLabBranch("master", true)));
261 Projects.CreateWsResponse response = ws.newRequest()
262 .setParam("almSetting", almSetting.getKey())
263 .setParam("gitlabProjectId", "12345")
264 .executeProtobuf(Projects.CreateWsResponse.class);
266 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
267 assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_BROWSER);
270 private AlmSettingDto configureUserAndPatAndAlmSettings() {
271 UserDto user = db.users().insertUser();
272 userSession.logIn(user).addPermission(PROVISION_PROJECTS);
273 return insertGitLabConfigurationAndPat(user);
276 private AlmSettingDto insertGitLabConfigurationAndPat(UserDto user) {
277 AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting();
278 db.almPats().insert(dto -> {
279 dto.setAlmSettingUuid(almSetting.getUuid());
280 dto.setUserUuid(user.getUuid());
281 dto.setPersonalAccessToken("PAT");
286 private Project mockGitlabProject(List<GitLabBranch> master) {
287 Project project = new Project(randomAlphanumeric(5), randomAlphanumeric(5));
288 when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project);
289 when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(master);
290 when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME);