]> source.dussan.org Git - sonarqube.git/blob
c06c5b9517b58f90b9ff5fe3ed2a2bf00fd59095
[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.developers.ws;
21
22 import java.io.UnsupportedEncodingException;
23 import java.net.URLEncoder;
24 import java.util.Date;
25 import java.util.stream.Stream;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.sonar.api.platform.Server;
29 import org.sonar.api.rules.RuleType;
30 import org.sonar.db.DbTester;
31 import org.sonar.db.ce.CeActivityDto;
32 import org.sonar.db.ce.CeQueueDto;
33 import org.sonar.db.ce.CeTaskTypes;
34 import org.sonar.db.component.BranchType;
35 import org.sonar.db.component.ComponentDto;
36 import org.sonar.db.component.ProjectData;
37 import org.sonar.db.component.SnapshotDto;
38 import org.sonar.db.rule.RuleDto;
39 import org.sonar.server.es.EsTester;
40 import org.sonar.server.issue.index.IssueIndex;
41 import org.sonar.server.issue.index.IssueIndexSyncProgressChecker;
42 import org.sonar.server.issue.index.IssueIndexer;
43 import org.sonar.server.issue.index.IssueIteratorFactory;
44 import org.sonar.server.tester.UserSessionRule;
45 import org.sonar.server.ws.WsActionTester;
46 import org.sonarqube.ws.Developers.SearchEventsWsResponse;
47 import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event;
48
49 import static java.lang.String.format;
50 import static java.nio.charset.StandardCharsets.UTF_8;
51 import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
52 import static org.apache.commons.lang.math.RandomUtils.nextInt;
53 import static org.apache.commons.lang.math.RandomUtils.nextLong;
54 import static org.assertj.core.api.Assertions.assertThat;
55 import static org.assertj.core.api.Assertions.tuple;
56 import static org.mockito.Mockito.mock;
57 import static org.mockito.Mockito.when;
58 import static org.sonar.api.utils.DateUtils.formatDateTime;
59 import static org.sonar.api.web.UserRole.USER;
60 import static org.sonar.db.component.BranchType.BRANCH;
61 import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_FROM;
62 import static org.sonar.server.developers.ws.SearchEventsAction.PARAM_PROJECTS;
63
64 public class SearchEventsActionNewIssuesIT {
65
66   private static final RuleType[] RULE_TYPES_EXCEPT_HOTSPOT = Stream.of(RuleType.values())
67     .filter(r -> r != RuleType.SECURITY_HOTSPOT)
68     .toArray(RuleType[]::new);
69
70   @Rule
71   public DbTester db = DbTester.create();
72   @Rule
73   public EsTester es = EsTester.create();
74   @Rule
75   public UserSessionRule userSession = UserSessionRule.standalone();
76
77   private Server server = mock(Server.class);
78
79   private IssueIndex issueIndex = new IssueIndex(es.client(), null, null, null);
80   private IssueIndexer issueIndexer = new IssueIndexer(es.client(), db.getDbClient(), new IssueIteratorFactory(db.getDbClient()), null);
81   private IssueIndexSyncProgressChecker issueIndexSyncProgressChecker = mock(IssueIndexSyncProgressChecker.class);
82   private WsActionTester ws = new WsActionTester(new SearchEventsAction(db.getDbClient(), userSession, server, issueIndex,
83     issueIndexSyncProgressChecker));
84
85   @Test
86   public void issue_event() {
87     userSession.logIn();
88     when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
89     ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
90     userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
91     SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
92     insertIssue(project, analysis);
93     insertIssue(project, analysis);
94     // will be ignored
95     insertSecurityHotspot(project, analysis);
96     issueIndexer.indexAllIssues();
97
98     long from = analysis.getCreatedAt() - 1_000_000L;
99     SearchEventsWsResponse result = ws.newRequest()
100       .setParam(PARAM_PROJECTS, project.getKey())
101       .setParam(PARAM_FROM, formatDateTime(from))
102       .executeProtobuf(SearchEventsWsResponse.class);
103
104     assertThat(result.getEventsList())
105       .extracting(Event::getCategory, Event::getProject, Event::getMessage, Event::getLink, Event::getDate)
106       .containsOnly(
107         tuple("NEW_ISSUES", project.getKey(), format("You have 2 new issues on project '%s'", project.name()),
108           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false", project.getKey(), encode(formatDateTime(from + 1_000L)),
109             userSession.getLogin()),
110           formatDateTime(analysis.getCreatedAt())));
111   }
112
113   @Test
114   public void many_issues_events() {
115     userSession.logIn();
116     long from = 1_500_000_000_000L;
117     ProjectData projectData = db.components().insertPrivateProject(p -> p.setName("SonarQube"));
118     ComponentDto mainBranchComponent = projectData.getMainBranchComponent();
119     userSession.addProjectPermission(USER, projectData.getProjectDto());
120     SnapshotDto analysis = insertAnalysis(mainBranchComponent, from);
121     insertIssue(mainBranchComponent, analysis);
122     insertIssue(mainBranchComponent, analysis);
123     issueIndexer.indexAllIssues();
124     String fromDate = formatDateTime(from - 1_000L);
125
126     SearchEventsWsResponse result = ws.newRequest()
127       .setParam(PARAM_PROJECTS, mainBranchComponent.getKey())
128       .setParam(PARAM_FROM, fromDate)
129       .executeProtobuf(SearchEventsWsResponse.class);
130
131     assertThat(result.getEventsList()).extracting(Event::getCategory, Event::getMessage, Event::getProject, Event::getDate)
132       .containsExactly(tuple("NEW_ISSUES", "You have 2 new issues on project 'SonarQube'", mainBranchComponent.getKey(),
133         formatDateTime(from)));
134   }
135
136   @Test
137   public void does_not_return_old_issue() {
138     userSession.logIn();
139     ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
140     userSession.addProjectPermission(USER, project);
141     SnapshotDto analysis = insertAnalysis(project, 1_500_000_000_000L);
142     db.issues().insert(db.rules().insert(), project, project, i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt() - 10_000L)));
143     issueIndexer.indexAllIssues();
144
145     SearchEventsWsResponse result = ws.newRequest()
146       .setParam(PARAM_PROJECTS, project.getKey())
147       .setParam(PARAM_FROM, formatDateTime(analysis.getCreatedAt() - 1_000L))
148       .executeProtobuf(SearchEventsWsResponse.class);
149
150     assertThat(result.getEventsList()).isEmpty();
151   }
152
153   @Test
154   public void return_link_to_issue_search_for_new_issues_event() {
155     userSession.logIn("my_login");
156     ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("my_project")).getMainBranchComponent();
157     userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
158     SnapshotDto analysis = insertAnalysis(project, 1_400_000_000_000L);
159     insertIssue(project, analysis);
160     issueIndexer.indexAllIssues();
161     when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
162
163     SearchEventsWsResponse result = ws.newRequest()
164       .setParam(PARAM_PROJECTS, project.getKey())
165       .setParam(PARAM_FROM, formatDateTime(analysis.getCreatedAt() - 1_000L))
166       .executeProtobuf(SearchEventsWsResponse.class);
167
168     assertThat(result.getEventsList()).extracting(Event::getLink)
169       .containsExactly("https://sonarcloud.io/project/issues?id=my_project&createdAfter=" + encode(formatDateTime(analysis.getCreatedAt())) + "&assignees=my_login&resolved=false");
170   }
171
172   @Test
173   public void branch_issues_events() {
174     userSession.logIn().setSystemAdministrator();
175     when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
176     ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
177     userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
178     String branchName1 = "branch1";
179     ComponentDto branch1 = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(branchName1));
180     SnapshotDto branch1Analysis = insertAnalysis(branch1, project.uuid(), 1_500_000_000_000L);
181     insertIssue(branch1, branch1Analysis);
182     insertIssue(branch1, branch1Analysis);
183     String branchName2 = "branch2";
184     ComponentDto branch2 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH).setKey(branchName2));
185     SnapshotDto branch2Analysis = insertAnalysis(branch2, project.uuid(), 1_300_000_000_000L);
186     insertIssue(branch2, branch2Analysis);
187     issueIndexer.indexAllIssues();
188
189     long from = 1_000_000_000_000L;
190     SearchEventsWsResponse result = ws.newRequest()
191       .setParam(PARAM_PROJECTS, project.getKey())
192       .setParam(PARAM_FROM, formatDateTime(from))
193       .executeProtobuf(SearchEventsWsResponse.class);
194
195     assertThat(result.getEventsList())
196       .extracting(Event::getCategory, Event::getProject, Event::getMessage, Event::getLink, Event::getDate)
197       .containsOnly(
198         tuple("NEW_ISSUES", project.getKey(), format("You have 2 new issues on project '%s' on branch '%s'", project.name(), branchName1),
199           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&branch=%s", branch1.getKey(), encode(formatDateTime(from + 1_000L)),
200             userSession.getLogin(), branchName1),
201           formatDateTime(branch1Analysis.getCreatedAt())),
202         tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on branch '%s'", project.name(), branchName2),
203           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&branch=%s", branch2.getKey(), encode(formatDateTime(from + 1_000L)),
204             userSession.getLogin(), branchName2),
205           formatDateTime(branch2Analysis.getCreatedAt())));
206   }
207
208   @Test
209   public void pull_request_issues_events() {
210     userSession.logIn().setSystemAdministrator();
211     when(server.getPublicRootUrl()).thenReturn("https://sonarcloud.io");
212     ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
213     userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
214     String nonMainBranchName = "nonMain";
215     ComponentDto nonMainBranch = db.components().insertProjectBranch(project, b -> b.setBranchType(BRANCH).setKey(nonMainBranchName));
216     SnapshotDto nonMainBranchAnalysis = insertAnalysis(nonMainBranch, project.uuid(), 1_500_000_000_000L);
217     insertIssue(nonMainBranch, nonMainBranchAnalysis);
218     insertIssue(nonMainBranch, nonMainBranchAnalysis);
219     String pullRequestKey = "42";
220     ComponentDto pullRequest = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.PULL_REQUEST).setKey(pullRequestKey));
221     SnapshotDto pullRequestAnalysis = insertAnalysis(pullRequest, project.uuid(), 1_300_000_000_000L);
222     insertIssue(pullRequest, pullRequestAnalysis);
223     issueIndexer.indexAllIssues();
224
225     long from = 1_000_000_000_000L;
226     SearchEventsWsResponse result = ws.newRequest()
227       .setParam(PARAM_PROJECTS, project.getKey())
228       .setParam(PARAM_FROM, formatDateTime(from))
229       .executeProtobuf(SearchEventsWsResponse.class);
230
231     assertThat(result.getEventsList())
232       .extracting(Event::getCategory, Event::getProject, Event::getMessage, Event::getLink, Event::getDate)
233       .containsOnly(
234         tuple("NEW_ISSUES", project.getKey(), format("You have 2 new issues on project '%s' on branch '%s'", project.name(), nonMainBranchName),
235           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&branch=%s", nonMainBranch.getKey(), encode(formatDateTime(from + 1_000L)),
236             userSession.getLogin(), nonMainBranchName),
237           formatDateTime(nonMainBranchAnalysis.getCreatedAt())),
238         tuple("NEW_ISSUES", project.getKey(), format("You have 1 new issue on project '%s' on pull request '%s'", project.name(), pullRequestKey),
239           format("https://sonarcloud.io/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false&pullRequest=%s", pullRequest.getKey(),
240             encode(formatDateTime(from + 1_000L)),
241             userSession.getLogin(), pullRequestKey),
242           formatDateTime(pullRequestAnalysis.getCreatedAt())));
243   }
244
245   @Test
246   public void encode_link() {
247     userSession.logIn("rågnar").setSystemAdministrator();
248     long from = 1_500_000_000_000L;
249     ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("M&M's")).getMainBranchComponent();
250     userSession.addProjectPermission(USER, db.components().getProjectDtoByMainBranch(project));
251     SnapshotDto analysis = insertAnalysis(project, from);
252     insertIssue(project, analysis);
253     issueIndexer.indexAllIssues();
254     when(server.getPublicRootUrl()).thenReturn("http://sonarcloud.io");
255
256     String fromDate = formatDateTime(from - 1_000L);
257     SearchEventsWsResponse result = ws.newRequest()
258       .setParam(PARAM_PROJECTS, project.getKey())
259       .setParam(PARAM_FROM, fromDate)
260       .executeProtobuf(SearchEventsWsResponse.class);
261
262     assertThat(result.getEventsList()).extracting(Event::getLink)
263       .containsExactly("http://sonarcloud.io/project/issues?id=M%26M%27s&createdAfter=" + encode(formatDateTime(from)) + "&assignees=r%C3%A5gnar&resolved=false");
264   }
265
266   private String encode(String text) {
267     try {
268       return URLEncoder.encode(text, UTF_8.name());
269     } catch (UnsupportedEncodingException e) {
270       throw new IllegalStateException(format("Cannot encode %s", text), e);
271     }
272   }
273
274   private void insertIssue(ComponentDto component, SnapshotDto analysis) {
275     RuleDto rule = db.rules().insert(r -> r.setType(randomRuleTypeExceptHotspot()));
276     db.issues().insert(rule, component, component,
277       i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt()))
278         .setAssigneeUuid(userSession.getUuid())
279         .setType(randomRuleTypeExceptHotspot()));
280   }
281
282   private void insertSecurityHotspot(ComponentDto component, SnapshotDto analysis) {
283     RuleDto rule = db.rules().insert(r -> r.setType(RuleType.SECURITY_HOTSPOT));
284     db.issues().insert(rule, component, component,
285       i -> i.setIssueCreationDate(new Date(analysis.getCreatedAt()))
286         .setAssigneeUuid(userSession.getUuid())
287         .setType(RuleType.SECURITY_HOTSPOT));
288   }
289
290
291   private SnapshotDto insertAnalysis(ComponentDto project, long analysisDate) {
292     SnapshotDto analysis = db.components().insertSnapshot(project, s -> s.setCreatedAt(analysisDate));
293     insertActivity(project.uuid(), analysis, CeActivityDto.Status.SUCCESS);
294     return analysis;
295   }
296
297   private SnapshotDto insertAnalysis(ComponentDto branch, String mainBranchUuid, long analysisDate) {
298     SnapshotDto analysis = db.components().insertSnapshot(branch, s -> s.setCreatedAt(analysisDate));
299     insertActivity(mainBranchUuid, analysis, CeActivityDto.Status.SUCCESS);
300     return analysis;
301   }
302
303   private CeActivityDto insertActivity(String mainBranchUuid, SnapshotDto analysis, CeActivityDto.Status status) {
304     CeQueueDto queueDto = new CeQueueDto();
305     queueDto.setTaskType(CeTaskTypes.REPORT);
306     queueDto.setComponentUuid(mainBranchUuid);
307     queueDto.setUuid(randomAlphanumeric(40));
308     queueDto.setCreatedAt(nextLong());
309     CeActivityDto activityDto = new CeActivityDto(queueDto);
310     activityDto.setStatus(status);
311     activityDto.setExecutionTimeMs(nextLong());
312     activityDto.setExecutedAt(nextLong());
313     activityDto.setAnalysisUuid(analysis.getUuid());
314     db.getDbClient().ceActivityDao().insert(db.getSession(), activityDto);
315     db.commit();
316     return activityDto;
317   }
318
319   private RuleType randomRuleTypeExceptHotspot() {
320     return RULE_TYPES_EXCEPT_HOTSPOT[nextInt(RULE_TYPES_EXCEPT_HOTSPOT.length)];
321   }
322 }