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.github;
22 import java.util.Optional;
23 import org.junit.Before;
24 import org.junit.Rule;
25 import org.junit.Test;
26 import org.sonar.alm.client.github.GithubApplicationClient;
27 import org.sonar.alm.client.github.GithubApplicationClientImpl;
28 import org.sonar.api.server.ws.WebService;
29 import org.sonar.api.utils.System2;
30 import org.sonar.core.i18n.I18n;
31 import org.sonar.core.util.SequenceUuidFactory;
32 import org.sonar.db.DbTester;
33 import org.sonar.db.alm.setting.AlmSettingDto;
34 import org.sonar.db.component.BranchDto;
35 import org.sonar.db.permission.GlobalPermission;
36 import org.sonar.db.project.ProjectDto;
37 import org.sonar.db.user.UserDto;
38 import org.sonar.server.almintegration.ws.ImportHelper;
39 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
40 import org.sonar.server.component.ComponentUpdater;
41 import org.sonar.server.es.TestProjectIndexers;
42 import org.sonar.server.exceptions.NotFoundException;
43 import org.sonar.server.exceptions.UnauthorizedException;
44 import org.sonar.server.favorite.FavoriteUpdater;
45 import org.sonar.server.permission.PermissionTemplateService;
46 import org.sonar.server.project.DefaultBranchNameResolver;
47 import org.sonar.server.project.ProjectDefaultVisibility;
48 import org.sonar.server.project.Visibility;
49 import org.sonar.server.tester.UserSessionRule;
50 import org.sonar.server.ws.TestRequest;
51 import org.sonar.server.ws.WsActionTester;
52 import org.sonarqube.ws.Projects;
54 import static org.assertj.core.api.Assertions.assertThat;
55 import static org.assertj.core.api.Assertions.assertThatThrownBy;
56 import static org.assertj.core.api.Assertions.tuple;
57 import static org.mockito.ArgumentMatchers.any;
58 import static org.mockito.Mockito.mock;
59 import static org.mockito.Mockito.when;
60 import static org.sonar.db.component.BranchDto.DEFAULT_PROJECT_MAIN_BRANCH_NAME;
61 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
62 import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_ORGANIZATION;
63 import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_REPOSITORY_KEY;
64 import static org.sonar.server.tester.UserSessionRule.standalone;
66 public class ImportGithubProjectActionTest {
68 private static final String PROJECT_KEY_NAME = "PROJECT_NAME";
71 public UserSessionRule userSession = standalone();
73 private final System2 system2 = mock(System2.class);
74 private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class);
75 private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class);
78 public DbTester db = DbTester.create(system2);
80 private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
81 mock(PermissionTemplateService.class), new FavoriteUpdater(db.getDbClient()), new TestProjectIndexers(), new SequenceUuidFactory(),
82 defaultBranchNameResolver);
84 private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
85 private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
86 private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
87 private final WsActionTester ws = new WsActionTester(new ImportGithubProjectAction(db.getDbClient(), userSession,
88 projectDefaultVisibility, appClient, componentUpdater, importHelper, projectKeyGenerator));
91 public void before() {
92 when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
93 when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_PROJECT_MAIN_BRANCH_NAME);
97 public void importProject_ifProjectWithSameNameDoesNotExist_importSucceed() {
98 AlmSettingDto githubAlmSetting = setupAlm();
99 db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid()));
101 GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false, "octocat/" + PROJECT_KEY_NAME,
102 "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "default-branch");
103 when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository));
104 when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME);
106 Projects.CreateWsResponse response = ws.newRequest()
107 .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
108 .setParam(PARAM_ORGANIZATION, "octocat")
109 .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
110 .executeProtobuf(Projects.CreateWsResponse.class);
112 Projects.CreateWsResponse.Project result = response.getProject();
113 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
114 assertThat(result.getName()).isEqualTo(repository.getName());
116 Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
117 assertThat(projectDto).isPresent();
118 assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
119 Optional<BranchDto> mainBranch = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()).stream().filter(BranchDto::isMain).findAny();
120 assertThat(mainBranch).isPresent();
121 assertThat(mainBranch.get().getKey()).isEqualTo("default-branch");
125 public void importProject_ifProjectWithSameNameAlreadyExists_importSucceed() {
126 AlmSettingDto githubAlmSetting = setupAlm();
127 db.almPats().insert(p -> p.setAlmSettingUuid(githubAlmSetting.getUuid()).setUserUuid(userSession.getUuid()));
128 db.components().insertPublicProject(p -> p.setKey("Hello-World"));
130 GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, "Hello-World", false, "Hello-World",
131 "https://github.sonarsource.com/api/v3/repos/octocat/Hello-World", "main");
132 when(appClient.getRepository(any(), any(), any(), any())).thenReturn(Optional.of(repository));
133 when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(PROJECT_KEY_NAME);
135 Projects.CreateWsResponse response = ws.newRequest()
136 .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
137 .setParam(PARAM_ORGANIZATION, "octocat")
138 .setParam(PARAM_REPOSITORY_KEY, "Hello-World")
139 .executeProtobuf(Projects.CreateWsResponse.class);
141 Projects.CreateWsResponse.Project result = response.getProject();
142 assertThat(result.getKey()).isEqualTo(PROJECT_KEY_NAME);
143 assertThat(result.getName()).isEqualTo(repository.getName());
147 public void fail_when_not_logged_in() {
148 TestRequest request = ws.newRequest()
149 .setParam(PARAM_ALM_SETTING, "asdfghjkl")
150 .setParam(PARAM_ORGANIZATION, "test")
151 .setParam(PARAM_REPOSITORY_KEY, "test/repo");
152 assertThatThrownBy(request::execute)
153 .isInstanceOf(UnauthorizedException.class);
157 public void fail_when_missing_create_project_permission() {
158 TestRequest request = ws.newRequest();
159 assertThatThrownBy(request::execute)
160 .isInstanceOf(UnauthorizedException.class);
164 public void fail_when_almSetting_does_not_exist() {
165 UserDto user = db.users().insertUser();
166 userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
168 TestRequest request = ws.newRequest()
169 .setParam(PARAM_ALM_SETTING, "unknown")
170 .setParam(PARAM_ORGANIZATION, "test")
171 .setParam(PARAM_REPOSITORY_KEY, "test/repo");
172 assertThatThrownBy(request::execute)
173 .isInstanceOf(NotFoundException.class)
174 .hasMessage("ALM Setting 'unknown' not found");
178 public void fail_when_personal_access_token_doesnt_exist() {
179 AlmSettingDto githubAlmSetting = setupAlm();
181 TestRequest request = ws.newRequest()
182 .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
183 .setParam(PARAM_ORGANIZATION, "test")
184 .setParam(PARAM_REPOSITORY_KEY, "test/repo");
185 assertThatThrownBy(request::execute)
186 .isInstanceOf(IllegalArgumentException.class)
187 .hasMessage("No personal access token found");
191 public void definition() {
192 WebService.Action def = ws.getDef();
194 assertThat(def.since()).isEqualTo("8.4");
195 assertThat(def.isPost()).isTrue();
196 assertThat(def.params())
197 .extracting(WebService.Param::key, WebService.Param::isRequired)
198 .containsExactlyInAnyOrder(
199 tuple(PARAM_ALM_SETTING, true),
200 tuple(PARAM_ORGANIZATION, true),
201 tuple(PARAM_REPOSITORY_KEY, true));
204 private AlmSettingDto setupAlm() {
205 UserDto user = db.users().insertUser();
206 userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
208 return db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123"));