]> source.dussan.org Git - sonarqube.git/blob
d4c0480940cb2c35886fb7823561ec752c377283
[sonarqube.git] /
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.github;
21
22 import java.util.Optional;
23 import java.util.Set;
24 import org.junit.Before;
25 import org.junit.Rule;
26 import org.junit.Test;
27 import org.mockito.ArgumentCaptor;
28 import org.sonar.alm.client.github.GithubApplicationClient;
29 import org.sonar.alm.client.github.GithubApplicationClientImpl;
30 import org.sonar.api.resources.Qualifiers;
31 import org.sonar.api.server.ws.WebService;
32 import org.sonar.api.utils.System2;
33 import org.sonar.auth.github.GitHubSettings;
34 import org.sonar.core.i18n.I18n;
35 import org.sonar.core.platform.EditionProvider;
36 import org.sonar.core.platform.PlatformEditionProvider;
37 import org.sonar.core.util.SequenceUuidFactory;
38 import org.sonar.db.DbSession;
39 import org.sonar.db.DbTester;
40 import org.sonar.db.alm.setting.AlmSettingDto;
41 import org.sonar.db.component.BranchDto;
42 import org.sonar.db.component.ResourceTypesRule;
43 import org.sonar.db.entity.EntityDto;
44 import org.sonar.db.newcodeperiod.NewCodePeriodDto;
45 import org.sonar.db.permission.GlobalPermission;
46 import org.sonar.db.project.CreationMethod;
47 import org.sonar.db.project.ProjectDto;
48 import org.sonar.db.user.UserDto;
49 import org.sonar.server.almintegration.ws.ImportHelper;
50 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
51 import org.sonar.server.almsettings.ws.GitHubDevOpsPlatformService;
52 import org.sonar.server.component.ComponentUpdater;
53 import org.sonar.server.es.EsTester;
54 import org.sonar.server.es.IndexersImpl;
55 import org.sonar.server.es.TestIndexers;
56 import org.sonar.server.exceptions.NotFoundException;
57 import org.sonar.server.exceptions.UnauthorizedException;
58 import org.sonar.server.favorite.FavoriteUpdater;
59 import org.sonar.server.management.ManagedProjectService;
60 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
61 import org.sonar.server.permission.GroupPermissionChanger;
62 import org.sonar.server.permission.PermissionService;
63 import org.sonar.server.permission.PermissionServiceImpl;
64 import org.sonar.server.permission.PermissionTemplateService;
65 import org.sonar.server.permission.PermissionUpdater;
66 import org.sonar.server.permission.UserPermissionChange;
67 import org.sonar.server.permission.UserPermissionChanger;
68 import org.sonar.server.permission.index.FooIndexDefinition;
69 import org.sonar.server.permission.index.PermissionIndexer;
70 import org.sonar.server.project.DefaultBranchNameResolver;
71 import org.sonar.server.project.ProjectDefaultVisibility;
72 import org.sonar.server.project.Visibility;
73 import org.sonar.server.tester.UserSessionRule;
74 import org.sonar.server.ws.TestRequest;
75 import org.sonar.server.ws.WsActionTester;
76 import org.sonarqube.ws.Projects;
77
78 import static java.util.Objects.requireNonNull;
79 import static org.assertj.core.api.Assertions.assertThat;
80 import static org.assertj.core.api.Assertions.assertThatNoException;
81 import static org.assertj.core.api.Assertions.assertThatThrownBy;
82 import static org.assertj.core.api.Assertions.tuple;
83 import static org.mockito.ArgumentMatchers.any;
84 import static org.mockito.ArgumentMatchers.eq;
85 import static org.mockito.Mockito.mock;
86 import static org.mockito.Mockito.never;
87 import static org.mockito.Mockito.verify;
88 import static org.mockito.Mockito.when;
89 import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
90 import static org.sonar.db.newcodeperiod.NewCodePeriodType.NUMBER_OF_DAYS;
91 import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
92 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
93 import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_ORGANIZATION;
94 import static org.sonar.server.almintegration.ws.github.ImportGithubProjectAction.PARAM_REPOSITORY_KEY;
95 import static org.sonar.server.tester.UserSessionRule.standalone;
96 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
97 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
98
99 public class ImportGithubProjectActionIT {
100
101   private static final String PROJECT_KEY_NAME = "PROJECT_NAME";
102   private static final String GENERATED_PROJECT_KEY = "generated_" + PROJECT_KEY_NAME;
103
104   @Rule
105   public UserSessionRule userSession = standalone();
106
107   private final System2 system2 = mock(System2.class);
108   private final GithubApplicationClientImpl appClient = mock(GithubApplicationClientImpl.class);
109   private final DefaultBranchNameResolver defaultBranchNameResolver = mock(DefaultBranchNameResolver.class);
110
111   @Rule
112   public DbTester db = DbTester.create(system2);
113   private final PermissionTemplateService permissionTemplateService = mock(PermissionTemplateService.class);
114   public EsTester es = EsTester.createCustom(new FooIndexDefinition());
115   private final PermissionUpdater<UserPermissionChange> userPermissionUpdater = new PermissionUpdater(
116     new IndexersImpl(new PermissionIndexer(db.getDbClient(), es.client())),
117     Set.of(new UserPermissionChanger(db.getDbClient(), new SequenceUuidFactory()),
118       new GroupPermissionChanger(db.getDbClient(), new SequenceUuidFactory())));
119   private final PermissionService permissionService = new PermissionServiceImpl(new ResourceTypesRule().setRootQualifiers(Qualifiers.PROJECT));
120   private final ComponentUpdater componentUpdater = new ComponentUpdater(db.getDbClient(), mock(I18n.class), System2.INSTANCE,
121     permissionTemplateService, new FavoriteUpdater(db.getDbClient()), new TestIndexers(), new SequenceUuidFactory(),
122     defaultBranchNameResolver, userPermissionUpdater, permissionService);
123
124   private final ImportHelper importHelper = new ImportHelper(db.getDbClient(), userSession);
125   private final ProjectKeyGenerator projectKeyGenerator = mock(ProjectKeyGenerator.class);
126   private final ProjectDefaultVisibility projectDefaultVisibility = mock(ProjectDefaultVisibility.class);
127   private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class);
128
129   private final GitHubSettings gitHubSettings = mock(GitHubSettings.class);
130   private final NewCodeDefinitionResolver newCodeDefinitionResolver = new NewCodeDefinitionResolver(db.getDbClient(), editionProvider);
131
132   private final ManagedProjectService managedProjectService = mock(ManagedProjectService.class);
133   private final GitHubDevOpsPlatformService gitHubDevOpsPlatformService = new GitHubDevOpsPlatformService(db.getDbClient(),
134     null, appClient, projectDefaultVisibility, projectKeyGenerator, userSession, componentUpdater, gitHubSettings);
135   private final WsActionTester ws = new WsActionTester(new ImportGithubProjectAction(db.getDbClient(), managedProjectService, userSession,
136     componentUpdater, importHelper, newCodeDefinitionResolver, defaultBranchNameResolver, gitHubDevOpsPlatformService));
137
138   @Before
139   public void before() {
140     when(projectDefaultVisibility.get(any())).thenReturn(Visibility.PRIVATE);
141     when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME);
142   }
143
144   @Test
145   public void importProject_ifProjectWithSameNameDoesNotExist_importSucceed() {
146     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
147
148     GithubApplicationClient.Repository repository = mockGithubInteractions();
149
150     Projects.CreateWsResponse response = callWebService(githubAlmSetting);
151
152     Projects.CreateWsResponse.Project result = response.getProject();
153     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
154     assertThat(result.getName()).isEqualTo(repository.getName());
155
156     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
157     assertThat(projectDto).isPresent();
158     assertThat(db.getDbClient().projectAlmSettingDao().selectByProject(db.getSession(), projectDto.get())).isPresent();
159     Optional<BranchDto> mainBranch = db.getDbClient().branchDao().selectByProject(db.getSession(), projectDto.get()).stream().filter(BranchDto::isMain).findAny();
160     assertThat(mainBranch).isPresent();
161     assertThat(mainBranch.get().getKey()).isEqualTo("default-branch");
162
163     verify(managedProjectService).queuePermissionSyncTask(userSession.getUuid(), mainBranch.get().getUuid(), projectDto.get().getUuid());
164   }
165
166   @Test
167   public void importProject_withNCD_developer_edition() {
168     when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
169
170     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
171
172     mockGithubInteractions();
173
174     Projects.CreateWsResponse response = ws.newRequest()
175       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
176       .setParam(PARAM_ORGANIZATION, "octocat")
177       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
178       .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
179       .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
180       .executeProtobuf(Projects.CreateWsResponse.class);
181
182     Projects.CreateWsResponse.Project result = response.getProject();
183     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
184
185     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
186     assertThat(projectDto).isPresent();
187
188     assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid()))
189       .isPresent()
190       .get()
191       .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
192       .containsExactly(NUMBER_OF_DAYS, "30", null);
193   }
194
195   @Test
196   public void importProject_withNCD_community_edition() {
197     when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY));
198
199     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
200
201     mockGithubInteractions();
202
203     Projects.CreateWsResponse response = ws.newRequest()
204       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
205       .setParam(PARAM_ORGANIZATION, "octocat")
206       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
207       .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "NUMBER_OF_DAYS")
208       .setParam(PARAM_NEW_CODE_DEFINITION_VALUE, "30")
209       .executeProtobuf(Projects.CreateWsResponse.class);
210
211     Projects.CreateWsResponse.Project result = response.getProject();
212     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
213
214     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
215     assertThat(projectDto).isPresent();
216     BranchDto branchDto = db.getDbClient().branchDao().selectMainBranchByProjectUuid(db.getSession(), projectDto.get().getUuid()).orElseThrow();
217
218     String projectUuid = projectDto.get().getUuid();
219     assertThat(db.getDbClient().newCodePeriodDao().selectByBranch(db.getSession(), projectUuid, branchDto.getUuid()))
220       .isPresent()
221       .get()
222       .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue, NewCodePeriodDto::getBranchUuid)
223       .containsExactly(NUMBER_OF_DAYS, "30", branchDto.getUuid());
224   }
225
226   @Test
227   public void importProject_reference_branch_ncd_no_default_branch() {
228     when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
229     when(defaultBranchNameResolver.getEffectiveMainBranchName()).thenReturn("default-branch");
230
231     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
232
233     mockGithubInteractions();
234
235     Projects.CreateWsResponse response = ws.newRequest()
236       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
237       .setParam(PARAM_ORGANIZATION, "octocat")
238       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
239       .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "reference_branch")
240       .executeProtobuf(Projects.CreateWsResponse.class);
241
242     Projects.CreateWsResponse.Project result = response.getProject();
243     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
244
245     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
246     assertThat(projectDto).isPresent();
247
248     assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid()))
249       .isPresent()
250       .get()
251       .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue)
252       .containsExactly(REFERENCE_BRANCH, "default-branch");
253   }
254
255   @Test
256   public void importProject_reference_branch_ncd() {
257     when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.DEVELOPER));
258
259     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
260
261     mockGithubInteractions();
262
263     Projects.CreateWsResponse response = ws.newRequest()
264       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
265       .setParam(PARAM_ORGANIZATION, "octocat")
266       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
267       .setParam(PARAM_NEW_CODE_DEFINITION_TYPE, "reference_branch")
268       .executeProtobuf(Projects.CreateWsResponse.class);
269
270     Projects.CreateWsResponse.Project result = response.getProject();
271     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
272
273     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), result.getKey());
274     assertThat(projectDto).isPresent();
275
276     assertThat(db.getDbClient().newCodePeriodDao().selectByProject(db.getSession(), projectDto.get().getUuid()))
277       .isPresent()
278       .get()
279       .extracting(NewCodePeriodDto::getType, NewCodePeriodDto::getValue)
280       .containsExactly(REFERENCE_BRANCH, "default-branch");
281   }
282
283   @Test
284   public void importProject_ifProjectWithSameNameAlreadyExists_importSucceed() {
285     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
286     db.components().insertPublicProject(p -> p.setKey("Hello-World")).getMainBranchComponent();
287
288     GithubApplicationClient.Repository repository = mockGithubInteractions();
289
290     Projects.CreateWsResponse response = ws.newRequest()
291       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
292       .setParam(PARAM_ORGANIZATION, "octocat")
293       .setParam(PARAM_REPOSITORY_KEY, "Hello-World")
294       .executeProtobuf(Projects.CreateWsResponse.class);
295
296     Projects.CreateWsResponse.Project result = response.getProject();
297     assertThat(result.getKey()).isEqualTo(GENERATED_PROJECT_KEY);
298     assertThat(result.getName()).isEqualTo(repository.getName());
299   }
300
301   @Test
302   public void importProject_whenGithubProvisioningIsDisabled_shouldApplyPermissionTemplate() {
303     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
304
305     mockGithubInteractions();
306     when(gitHubSettings.isProvisioningEnabled()).thenReturn(false);
307
308     ws.newRequest()
309       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
310       .setParam(PARAM_ORGANIZATION, "octocat")
311       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
312       .executeProtobuf(Projects.CreateWsResponse.class);
313
314     ArgumentCaptor<EntityDto> projectDtoArgumentCaptor = ArgumentCaptor.forClass(EntityDto.class);
315     verify(permissionTemplateService).applyDefaultToNewComponent(any(DbSession.class), projectDtoArgumentCaptor.capture(), eq(userSession.getUuid()));
316     String projectKey = projectDtoArgumentCaptor.getValue().getKey();
317     assertThat(projectKey).isEqualTo(GENERATED_PROJECT_KEY);
318
319   }
320
321   @Test
322   public void importProject_whenGithubProvisioningIsEnabled_shouldNotApplyPermissionTemplate() {
323     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
324
325     mockGithubInteractions();
326     when(gitHubSettings.isProvisioningEnabled()).thenReturn(true);
327
328     ws.newRequest()
329       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
330       .setParam(PARAM_ORGANIZATION, "octocat")
331       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
332       .executeProtobuf(Projects.CreateWsResponse.class);
333
334     verify(permissionTemplateService, never()).applyDefaultToNewComponent(any(), any(), any());
335
336   }
337
338   @Test
339   public void importProject_shouldSetCreationMethodToApi_ifNonBrowserRequest() {
340     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
341     mockGithubInteractions();
342
343     Projects.CreateWsResponse response = callWebService(githubAlmSetting);
344
345     assertThat(response.getProject().getKey()).isEqualTo(GENERATED_PROJECT_KEY);
346     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
347     assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_API);
348   }
349
350   @Test
351   public void importProject_shouldSetCreationMethodToBrowser_ifBrowserRequest() {
352     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
353     userSession.flagSessionAsGui();
354     mockGithubInteractions();
355
356     Projects.CreateWsResponse response = callWebService(githubAlmSetting);
357
358     assertThat(response.getProject().getKey()).isEqualTo(GENERATED_PROJECT_KEY);
359     Optional<ProjectDto> projectDto = db.getDbClient().projectDao().selectProjectByKey(db.getSession(), response.getProject().getKey());
360     assertThat(projectDto.orElseThrow().getCreationMethod()).isEqualTo(CreationMethod.ALM_IMPORT_BROWSER);
361   }
362
363   @Test
364   public void importProject_whenAlmSettingKeyDoesNotExist_shouldThrow() {
365     UserDto user = db.users().insertUser();
366     userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
367
368     TestRequest request = ws.newRequest()
369       .setParam(PARAM_ALM_SETTING, "unknown")
370       .setParam(PARAM_ORGANIZATION, "test")
371       .setParam(PARAM_REPOSITORY_KEY, "test/repo");
372     assertThatThrownBy(request::execute)
373       .isInstanceOf(NotFoundException.class)
374       .hasMessage("DevOps Platform configuration 'unknown' not found.");
375   }
376
377   @Test
378   public void importProject_whenNoAlmSettingKeyAndNoConfig_shouldThrow() {
379     UserDto user = db.users().insertUser();
380     userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
381
382     TestRequest request = ws.newRequest()
383       .setParam(PARAM_ORGANIZATION, "test")
384       .setParam(PARAM_REPOSITORY_KEY, "test/repo");
385     assertThatThrownBy(request::execute)
386       .isInstanceOf(NotFoundException.class)
387       .hasMessage("There is no GITHUB configuration for DevOps Platform. Please add one.");
388   }
389
390   @Test
391   public void importProject_whenNoAlmSettingKeyAndMultipleConfigs_shouldThrow() {
392     UserDto user = db.users().insertUser();
393     userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
394     db.almSettings().insertGitHubAlmSetting();
395     db.almSettings().insertGitHubAlmSetting();
396
397     TestRequest request = ws.newRequest()
398       .setParam(PARAM_ORGANIZATION, "test")
399       .setParam(PARAM_REPOSITORY_KEY, "test/repo");
400     assertThatThrownBy(request::execute)
401       .isInstanceOf(IllegalArgumentException.class)
402       .hasMessage("Parameter almSetting is required as there are multiple DevOps Platform configurations.");
403   }
404
405   @Test
406   public void importProject_whenNoAlmSettingKeyAndOnlyOneConfig_shouldImport() {
407     AlmSettingDto githubAlmSetting = setupUserWithPatAndAlmSettings();
408
409     mockGithubInteractions();
410     when(gitHubSettings.isProvisioningEnabled()).thenReturn(true);
411
412     TestRequest request = ws.newRequest()
413       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
414       .setParam(PARAM_ORGANIZATION, "octocat")
415       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME);
416
417     assertThatNoException().isThrownBy(request::execute);
418   }
419
420   private Projects.CreateWsResponse callWebService(AlmSettingDto githubAlmSetting) {
421     return ws.newRequest()
422       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
423       .setParam(PARAM_ORGANIZATION, "octocat")
424       .setParam(PARAM_REPOSITORY_KEY, "octocat/" + PROJECT_KEY_NAME)
425       .executeProtobuf(Projects.CreateWsResponse.class);
426   }
427
428   private GithubApplicationClient.Repository mockGithubInteractions() {
429     GithubApplicationClient.Repository repository = new GithubApplicationClient.Repository(1L, PROJECT_KEY_NAME, false,
430       "octocat/" + PROJECT_KEY_NAME,
431       "https://github.sonarsource.com/api/v3/repos/octocat/" + PROJECT_KEY_NAME, "default-branch");
432     when(appClient.getRepository(any(), any(), any())).thenReturn(Optional.of(repository));
433     when(projectKeyGenerator.generateUniqueProjectKey(repository.getFullName())).thenReturn(GENERATED_PROJECT_KEY);
434     return repository;
435   }
436
437   @Test
438   public void fail_when_not_logged_in() {
439     TestRequest request = ws.newRequest()
440       .setParam(PARAM_ALM_SETTING, "asdfghjkl")
441       .setParam(PARAM_ORGANIZATION, "test")
442       .setParam(PARAM_REPOSITORY_KEY, "test/repo");
443     assertThatThrownBy(request::execute)
444       .isInstanceOf(UnauthorizedException.class);
445   }
446
447   @Test
448   public void fail_when_missing_create_project_permission() {
449     TestRequest request = ws.newRequest();
450     assertThatThrownBy(request::execute)
451       .isInstanceOf(UnauthorizedException.class);
452   }
453
454   @Test
455   public void fail_when_personal_access_token_doesnt_exist() {
456     AlmSettingDto githubAlmSetting = setupUserAndAlmSettings();
457
458     TestRequest request = ws.newRequest()
459       .setParam(PARAM_ALM_SETTING, githubAlmSetting.getKey())
460       .setParam(PARAM_ORGANIZATION, "test")
461       .setParam(PARAM_REPOSITORY_KEY, "test/repo");
462     assertThatThrownBy(request::execute)
463       .isInstanceOf(IllegalArgumentException.class)
464       .hasMessage("No personal access token found");
465   }
466
467   @Test
468   public void definition() {
469     WebService.Action def = ws.getDef();
470
471     assertThat(def.since()).isEqualTo("8.4");
472     assertThat(def.isPost()).isTrue();
473     assertThat(def.params())
474       .extracting(WebService.Param::key, WebService.Param::isRequired)
475       .containsExactlyInAnyOrder(
476         tuple(PARAM_ALM_SETTING, false),
477         tuple(PARAM_ORGANIZATION, true),
478         tuple(PARAM_REPOSITORY_KEY, true),
479         tuple(PARAM_NEW_CODE_DEFINITION_TYPE, false),
480         tuple(PARAM_NEW_CODE_DEFINITION_VALUE, false));
481   }
482
483   private AlmSettingDto setupUserWithPatAndAlmSettings() {
484     AlmSettingDto almSettings = setupUserAndAlmSettings();
485     db.almPats().insert(p -> p.setAlmSettingUuid(almSettings.getUuid()).setUserUuid(requireNonNull(userSession.getUuid())));
486     return almSettings;
487   }
488
489   private AlmSettingDto setupUserAndAlmSettings() {
490     UserDto user = db.users().insertUser();
491     userSession.logIn(user).addPermission(GlobalPermission.PROVISION_PROJECTS);
492     return db.almSettings().insertGitHubAlmSetting(alm -> alm.setClientId("client_123").setClientSecret("client_secret_123"));
493   }
494 }