]> source.dussan.org Git - sonarqube.git/blob
5df514c857e5776d283ba8afefb4d0933ee8529d
[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.alm.client.github;
21
22 import com.google.gson.Gson;
23 import com.google.gson.reflect.TypeToken;
24 import java.io.IOException;
25 import java.lang.reflect.Type;
26 import java.util.List;
27 import java.util.Optional;
28 import org.junit.Rule;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.ArgumentCaptor;
32 import org.mockito.InjectMocks;
33 import org.mockito.Mock;
34 import org.mockito.junit.MockitoJUnitRunner;
35 import org.slf4j.event.Level;
36 import org.sonar.alm.client.github.security.AccessToken;
37 import org.sonar.api.testfixtures.log.LogTester;
38
39 import static org.assertj.core.api.Assertions.assertThat;
40 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
41 import static org.assertj.core.api.Assertions.assertThatNoException;
42 import static org.mockito.ArgumentMatchers.any;
43 import static org.mockito.ArgumentMatchers.eq;
44 import static org.mockito.Mockito.doThrow;
45 import static org.mockito.Mockito.mock;
46 import static org.mockito.Mockito.verify;
47 import static org.mockito.Mockito.when;
48 import static org.sonar.alm.client.github.ApplicationHttpClient.GetResponse;
49
50 @RunWith(MockitoJUnitRunner.class)
51 public class GithubPaginatedHttpClientImplTest {
52
53   private static final String APP_URL = "https://github.com/";
54
55   private static final String ENDPOINT = "/test-endpoint";
56
57   private static final Type STRING_LIST_TYPE = TypeToken.getParameterized(List.class, String.class).getType();
58
59   private Gson gson = new Gson();
60
61   @Rule
62   public LogTester logTester = new LogTester();
63
64   @Mock
65   private AccessToken accessToken;
66
67   @Mock
68   RatioBasedRateLimitChecker rateLimitChecker;
69
70   @Mock
71   ApplicationHttpClient appHttpClient;
72
73   @InjectMocks
74   private GithubPaginatedHttpClient underTest;
75
76   @Test
77   public void get_whenNoPagination_ReturnsCorrectResponse() throws IOException {
78
79     GetResponse response = mockResponseWithoutPagination("[\"result1\", \"result2\"]");
80     when(appHttpClient.get(APP_URL, accessToken, ENDPOINT + "?per_page=100")).thenReturn(response);
81
82     List<String> results = underTest.get(APP_URL, accessToken, ENDPOINT, result -> gson.fromJson(result, STRING_LIST_TYPE));
83
84     assertThat(results)
85       .containsExactly("result1", "result2");
86   }
87
88   @Test
89   public void get_whenEndpointAlreadyContainsPathParameter_shouldAddANewParameter() throws IOException {
90     ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
91
92     GetResponse response = mockResponseWithoutPagination("[\"result1\", \"result2\"]");
93     when(appHttpClient.get(eq(APP_URL), eq(accessToken), urlCaptor.capture())).thenReturn(response);
94
95     underTest.get(APP_URL, accessToken, ENDPOINT + "?alreadyExistingArg=2", result -> gson.fromJson(result, STRING_LIST_TYPE));
96
97     assertThat(urlCaptor.getValue()).isEqualTo(ENDPOINT + "?alreadyExistingArg=2&per_page=100");
98   }
99
100   private static GetResponse mockResponseWithoutPagination(String content) {
101     GetResponse response = mock(GetResponse.class);
102     when(response.getCode()).thenReturn(200);
103     when(response.getContent()).thenReturn(Optional.of(content));
104     return response;
105   }
106
107   @Test
108   public void get_whenPaginationAndRateLimiting_returnsResponseFromAllPages() throws IOException, InterruptedException {
109     GetResponse response1 = mockResponseWithPaginationAndRateLimit("[\"result1\", \"result2\"]", "/next-endpoint");
110     GetResponse response2 = mockResponseWithoutPagination("[\"result3\"]");
111     when(appHttpClient.get(APP_URL, accessToken, ENDPOINT + "?per_page=100")).thenReturn(response1);
112     when(appHttpClient.get(APP_URL, accessToken, "/next-endpoint")).thenReturn(response2);
113
114     List<String> results = underTest.get(APP_URL, accessToken, ENDPOINT, result -> gson.fromJson(result, STRING_LIST_TYPE));
115
116     assertThat(results)
117       .containsExactly("result1", "result2", "result3");
118
119     ArgumentCaptor<ApplicationHttpClient.RateLimit> rateLimitRecordCaptor = ArgumentCaptor.forClass(ApplicationHttpClient.RateLimit.class);
120     verify(rateLimitChecker).checkRateLimit(rateLimitRecordCaptor.capture());
121     ApplicationHttpClient.RateLimit rateLimitRecord = rateLimitRecordCaptor.getValue();
122     assertThat(rateLimitRecord.limit()).isEqualTo(10);
123     assertThat(rateLimitRecord.remaining()).isEqualTo(1);
124     assertThat(rateLimitRecord.reset()).isZero();
125   }
126
127   private static GetResponse mockResponseWithPaginationAndRateLimit(String content, String nextEndpoint) {
128     GetResponse response = mockResponseWithoutPagination(content);
129     when(response.getCode()).thenReturn(200);
130     when(response.getNextEndPoint()).thenReturn(Optional.of(nextEndpoint));
131     when(response.getRateLimit()).thenReturn(new ApplicationHttpClient.RateLimit(1, 10, 0L));
132     return response;
133   }
134
135   @Test
136   public void get_whenGitHubReturnsNonSuccessCode_shouldThrow() throws IOException {
137     GetResponse response1 = mockResponseWithPaginationAndRateLimit("[\"result1\", \"result2\"]", "/next-endpoint");
138     GetResponse response2 = mockFailedResponse("failed");
139     when(appHttpClient.get(APP_URL, accessToken, ENDPOINT + "?per_page=100")).thenReturn(response1);
140     when(appHttpClient.get(APP_URL, accessToken, "/next-endpoint")).thenReturn(response2);
141
142     assertThatIllegalStateException()
143       .isThrownBy(() -> underTest.get(APP_URL, accessToken, ENDPOINT, result -> gson.fromJson(result, STRING_LIST_TYPE)))
144       .withMessage("Error while executing a call to GitHub. Return code 400. Error message: failed.");
145   }
146
147   private static GetResponse mockFailedResponse(String content) {
148     GetResponse response = mock(GetResponse.class);
149     when(response.getCode()).thenReturn(400);
150     when(response.getContent()).thenReturn(Optional.of(content));
151     return response;
152   }
153
154   @Test
155   public void getRepositoryTeams_whenRateLimitCheckerThrowsInterruptedException_shouldSucceed() throws IOException, InterruptedException {
156     GetResponse response1 = mockResponseWithPaginationAndRateLimit("[\"result1\", \"result2\"]", "/next-endpoint");
157     GetResponse response2 = mockResponseWithoutPagination("[\"result3\"]");
158     when(appHttpClient.get(APP_URL, accessToken, ENDPOINT + "?per_page=100")).thenReturn(response1);
159     when(appHttpClient.get(APP_URL, accessToken, "/next-endpoint")).thenReturn(response2);
160     doThrow(new InterruptedException("interrupted")).when(rateLimitChecker).checkRateLimit(any(ApplicationHttpClient.RateLimit.class));
161
162     assertThatNoException()
163       .isThrownBy(() -> underTest.get(APP_URL, accessToken, ENDPOINT, result -> gson.fromJson(result, STRING_LIST_TYPE)));
164
165     assertThat(logTester.logs()).hasSize(1);
166     assertThat(logTester.logs(Level.WARN))
167       .containsExactly("Thread interrupted: interrupted");
168   }
169 }