You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImportGitLabProjectActionIT.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  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.
  10. *
  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.
  15. *
  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.
  19. */
  20. package org.sonar.server.almintegration.ws.gitlab;
  21. import java.util.List;
  22. import java.util.Optional;
  23. import org.assertj.core.api.Assertions;
  24. import org.junit.Before;
  25. import org.junit.Rule;
  26. import org.junit.Test;
  27. import org.sonar.alm.client.gitlab.GitLabBranch;
  28. import org.sonar.alm.client.gitlab.GitlabHttpClient;
  29. import org.sonar.alm.client.gitlab.Project;
  30. import org.sonar.api.utils.System2;
  31. import org.sonar.core.i18n.I18n;
  32. import org.sonar.core.platform.EditionProvider;
  33. import org.sonar.core.platform.PlatformEditionProvider;
  34. import org.sonar.core.util.SequenceUuidFactory;
  35. import org.sonar.db.DbTester;
  36. import org.sonar.db.alm.setting.AlmSettingDto;
  37. import org.sonar.db.component.BranchDto;
  38. import org.sonar.db.newcodeperiod.NewCodePeriodDto;
  39. import org.sonar.db.project.CreationMethod;
  40. import org.sonar.db.project.ProjectDto;
  41. import org.sonar.db.user.UserDto;
  42. import org.sonar.server.almintegration.ws.ImportHelper;
  43. import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
  44. import org.sonar.server.component.ComponentUpdater;
  45. import org.sonar.server.es.TestIndexers;
  46. import org.sonar.server.exceptions.NotFoundException;
  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.TestRequest;
  57. import org.sonar.server.ws.WsActionTester;
  58. 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.assertThatNoException;
  64. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  65. import static org.assertj.core.api.Assertions.tuple;
  66. import static org.mockito.ArgumentMatchers.any;
  67. import static org.mockito.Mockito.mock;
  68. import static org.mockito.Mockito.verify;
  69. import static org.mockito.Mockito.when;
  70. import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
  71. import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
  72. import static org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS;
  73. import static org.sonar.server.tester.UserSessionRule.standalone;
  74. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
  75. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
  76. public class ImportGitLabProjectActionIT {
  77. private static final String PROJECT_KEY_NAME = "PROJECT_NAME";
  78. private final System2 system2 = mock(System2.class);
  79. @Rule
  80. public UserSessionRule userSession = standalone();
  81. @Rule
  82. public DbTester db = DbTester.create(system2);
  83. DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class);
  84. private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
  85. mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(),
  86. defaultBranchNameResolver, mock(PermissionUpdater.class), mock(PermissionService.class));
  87. private final GitlabHttpClient gitlabHttpClient = mock(GitlabHttpClient.class);
  88. private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
  89. private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
  90. private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
  91. private PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
  92. private NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider);
  93. private final ImportGitLabProjectAction importGitLabProjectAction = new ImportGitLabProjectAction(
  94. db.getDbClient(), userSession, projectDefaultVisibility, gitlabHttpClient, componentUpdater, importHelper, projectKeyGenerator, newCodeDefinitionResolver,
  95. defaultBranchNameResolver);
  96. private final WsActionTester ws = new WsActionTester(importGitLabProjectAction);
  97. @Before
  98. public void before() {
  99. when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
  100. when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME);
  101. }
  102. @Test
  103. public void import_project_developer_edition() {
  104. when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
  105. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  106. Project project = mockGitlabProject(singletonList(new GitLabBranch("master", true)));
  107. Projects.CreateWsResponse response = ws.newRequest()
  108. .setParam("almSetting", almSetting.getKey())
  109. .setParam("gitlabProjectId", "12345")
  110. .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
  111. .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
  112. .executeProtobuf(Projects.CreateWsResponse.class);
  113. verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
  114. Projects.CreateWsResponse.Project result = response.getProject();
  115. assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
  116. assertThat(result.getName()).isEqualTo(project.getName());
  117. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
  118. assertThat(projectDto).isPresent();
  119. assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
  120. assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid()))
  121. .isPresent()
  122. .get()
  123. .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
  124. .containsExactly(NUMBER_OF_DAYS, "30", null);
  125. }
  126. @Test
  127. public void import_project_community_edition() {
  128. when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
  129. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  130. mockGitlabProject(singletonList(new GitLabBranch("master", true)));
  131. Projects.CreateWsResponse response = ws.newRequest()
  132. .setParam("almSetting", almSetting.getKey())
  133. .setParam("gitlabProjectId", "12345")
  134. .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
  135. .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
  136. .executeProtobuf(Projects.CreateWsResponse.class);
  137. Projects.CreateWsResponse.Project result = response.getProject();
  138. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
  139. BranchDto branchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(db.getSession(), projectDto.get().getUuid()).orElseThrow();
  140. String projectUuid = projectDto.get().getUuid();
  141. assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, branchDto.getUuid()))
  142. .isPresent()
  143. .get()
  144. .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
  145. .containsExactly(NUMBER_OF_DAYS, "30", branchDto.getUuid());
  146. }
  147. @Test
  148. public void import_project_with_specific_different_default_branch() {
  149. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  150. Project project = mockGitlabProject(singletonList(new GitLabBranch("main", true)));
  151. Projects.CreateWsResponse response = ws.newRequest()
  152. .setParam("almSetting", almSetting.getKey())
  153. .setParam("gitlabProjectId", "12345")
  154. .executeProtobuf(Projects.CreateWsResponse.class);
  155. verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
  156. verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L);
  157. Projects.CreateWsResponse.Project result = response.getProject();
  158. assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
  159. assertThat(result.getName()).isEqualTo(project.getName());
  160. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
  161. assertThat(projectDto).isPresent();
  162. assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
  163. Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()))
  164. .extracting(BranchDto::getKey, BranchDto::isMain)
  165. .containsExactlyInAnyOrder(tuple("main", true));
  166. }
  167. @Test
  168. public void import_project_no_gitlab_default_branch() {
  169. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  170. Project project = mockGitlabProject(emptyList());
  171. Projects.CreateWsResponse response = ws.newRequest()
  172. .setParam("almSetting", almSetting.getKey())
  173. .setParam("gitlabProjectId", "12345")
  174. .executeProtobuf(Projects.CreateWsResponse.class);
  175. verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
  176. verify(gitlabHttpClient).getBranches(almSetting.getUrl(), "PAT", 12345L);
  177. Projects.CreateWsResponse.Project result = response.getProject();
  178. assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
  179. assertThat(result.getName()).isEqualTo(project.getName());
  180. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
  181. assertThat(projectDto).isPresent();
  182. assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
  183. Assertions.assertThat(db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()))
  184. .extracting(BranchDto::getKey, BranchDto::isMain)
  185. .containsExactlyInAnyOrder(tuple(DEFAULT_MAIN_BRANCH_NAME, true));
  186. }
  187. @Test
  188. public void import_project_without_NCD() {
  189. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  190. Project project = mockGitlabProject(singletonList(new GitLabBranch("master", true)));
  191. Projects.CreateWsResponse response = ws.newRequest()
  192. .setParam("almSetting", almSetting.getKey())
  193. .setParam("gitlabProjectId", "12345")
  194. .executeProtobuf(Projects.CreateWsResponse.class);
  195. verify(gitlabHttpClient).getProject(almSetting.getUrl(), "PAT", 12345L);
  196. Projects.CreateWsResponse.Project result = response.getProject();
  197. assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
  198. assertThat(result.getName()).isEqualTo(project.getName());
  199. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
  200. assertThat(projectDto).isPresent();
  201. assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
  202. }
  203. @Test
  204. public void importProject_whenNonBrowserCall_setsCreationMethodToApi() {
  205. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  206. mockGitlabProject(singletonList(new GitLabBranch("master", true)));
  207. Projects.CreateWsResponse response = ws.newRequest()
  208. .setParam("almSetting", almSetting.getKey())
  209. .setParam("gitlabProjectId", "12345")
  210. .executeProtobuf(Projects.CreateWsResponse.class);
  211. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
  212. assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_API);
  213. }
  214. @Test
  215. public void importProject_whenBrowserCall_setsCreationMethodToBrowser() {
  216. AlmSettingDto almSetting = configureUserAndPatAndAlmSettings();
  217. userSession.flagSessionAsGui();
  218. mockGitlabProject(singletonList(new GitLabBranch("master", true)));
  219. Projects.CreateWsResponse response = ws.newRequest()
  220. .setParam("almSetting", almSetting.getKey())
  221. .setParam("gitlabProjectId", "12345")
  222. .executeProtobuf(Projects.CreateWsResponse.class);
  223. Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
  224. assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_BROWSER);
  225. }
  226. @Test
  227. public void importProject_whenAlmSettingKeyDoesNotExist_shouldThrow() {
  228. UserDto user = db.users().insertUser();
  229. userSession.logIn(user).addPermission(PROVISION_PROJECTS);
  230. TestRequest request = ws.newRequest()
  231. .setParam("almSetting", "unknown")
  232. .setParam("gitlabProjectId", "12345");
  233. assertThatThrownBy(request::execute)
  234. .isInstanceOf(NotFoundException.class)
  235. .hasMessage("DevOps Platform configuration 'unknown' not found.");
  236. }
  237. @Test
  238. public void importProject_whenNoAlmSettingKeyAndNoConfig_shouldThrow() {
  239. UserDto user = db.users().insertUser();
  240. userSession.logIn(user).addPermission(PROVISION_PROJECTS);
  241. TestRequest request = ws.newRequest()
  242. .setParam("gitlabProjectId", "12345");
  243. assertThatThrownBy(request::execute)
  244. .isInstanceOf(NotFoundException.class)
  245. .hasMessage("There is no GITLAB configuration for DevOps Platform. Please add one.");
  246. }
  247. @Test
  248. public void importProject_whenNoAlmSettingKeyAndMultipleConfigs_shouldThrow() {
  249. UserDto user = db.users().insertUser();
  250. userSession.logIn(user).addPermission(PROVISION_PROJECTS);
  251. db.almSettings().insertGitlabAlmSetting();
  252. db.almSettings().insertGitlabAlmSetting();
  253. TestRequest request = ws.newRequest()
  254. .setParam("gitlabProjectId", "12345");
  255. assertThatThrownBy(request::execute)
  256. .isInstanceOf(IllegalArgumentException.class)
  257. .hasMessage("Parameter almSetting is required as there are multiple DevOps Platform configurations.");
  258. }
  259. @Test
  260. public void importProject_whenNoAlmSettingKeyAndOnlyOneConfig_shouldImport() {
  261. configureUserAndPatAndAlmSettings();
  262. mockGitlabProject(emptyList());
  263. TestRequest request = ws.newRequest()
  264. .setParam("gitlabProjectId", "12345");
  265. assertThatNoException().isThrownBy(request::execute);
  266. }
  267. private AlmSettingDto configureUserAndPatAndAlmSettings() {
  268. UserDto user = db.users().insertUser();
  269. userSession.logIn(user).addPermission(PROVISION_PROJECTS);
  270. return insertGitLabConfigurationAndPat(user);
  271. }
  272. private AlmSettingDto insertGitLabConfigurationAndPat(UserDto user) {
  273. AlmSettingDto almSetting = db.almSettings().insertGitlabAlmSetting();
  274. db.almPats().insert(dto -> {
  275. dto.setAlmSettingUuid(almSetting.getUuid());
  276. dto.setUserUuid(user.getUuid());
  277. dto.setPersonalAccessToken("PAT");
  278. });
  279. return almSetting;
  280. }
  281. private Project mockGitlabProject(List<GitLabBranch> master) {
  282. Project project = new Project(randomAlphanumeric(5), randomAlphanumeric(5));
  283. when(gitlabHttpClient.getProject(any(), any(), any())).thenReturn(project);
  284. when(gitlabHttpClient.getBranches(any(), any(), any())).thenReturn(master);
  285. when(projectKeyGenerator.generateUniqueProjectKey(project.getPathWithNamespace())).thenReturn(PROJECT_KEY_NAME);
  286. return project;
  287. }
  288. }