3 * Copyright (C) 2009-2024 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.qualitygate.changeevent;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableSet;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.LinkedHashSet;
28 import java.util.List;
29 import java.util.Random;
31 import java.util.stream.Stream;
32 import org.apache.commons.lang3.RandomStringUtils;
33 import org.assertj.core.groups.Tuple;
34 import org.junit.Before;
35 import org.junit.Rule;
36 import org.junit.Test;
37 import org.mockito.ArgumentCaptor;
38 import org.mockito.InOrder;
39 import org.mockito.Mockito;
40 import org.slf4j.event.Level;
41 import org.sonar.api.issue.Issue;
42 import org.sonar.api.rules.RuleType;
43 import org.sonar.api.testfixtures.log.LogTester;
44 import org.sonar.core.issue.DefaultIssue;
45 import org.sonar.db.component.BranchDto;
46 import org.sonar.server.qualitygate.changeevent.QGChangeEventListener.ChangedIssue;
48 import static java.lang.String.format;
49 import static java.util.Collections.emptyList;
50 import static java.util.Collections.emptySet;
51 import static java.util.Collections.singletonList;
52 import static org.assertj.core.api.Assertions.assertThat;
53 import static org.assertj.core.api.Assertions.tuple;
54 import static org.junit.Assert.fail;
55 import static org.mockito.ArgumentMatchers.any;
56 import static org.mockito.ArgumentMatchers.same;
57 import static org.mockito.Mockito.doThrow;
58 import static org.mockito.Mockito.mock;
59 import static org.mockito.Mockito.verify;
60 import static org.mockito.Mockito.verifyNoInteractions;
61 import static org.mockito.Mockito.verifyNoMoreInteractions;
62 import static org.mockito.Mockito.when;
64 public class QGChangeEventListenersImplTest {
66 public LogTester logTester = new LogTester();
68 private final QGChangeEventListener listener1 = mock(QGChangeEventListener.class);
69 private final QGChangeEventListener listener2 = mock(QGChangeEventListener.class);
70 private final QGChangeEventListener listener3 = mock(QGChangeEventListener.class);
71 private final List<QGChangeEventListener> listeners = Arrays.asList(listener1, listener2, listener3);
73 private final String project1Uuid = RandomStringUtils.secure().nextAlphabetic(6);
74 private final BranchDto project1 = newBranchDto(project1Uuid);
75 private final DefaultIssue component1Issue = newDefaultIssue(project1Uuid);
76 private final List<DefaultIssue> oneIssueOnComponent1 = singletonList(component1Issue);
77 private final QGChangeEvent component1QGChangeEvent = newQGChangeEvent(project1);
79 private final InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3);
81 private final QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(new LinkedHashSet<>(List.of(listener1, listener2, listener3)));
84 public void before() {
85 logTester.setLevel(Level.TRACE);
89 public void broadcastOnIssueChange_has_no_effect_when_issues_are_empty() {
90 underTest.broadcastOnIssueChange(emptyList(), singletonList(component1QGChangeEvent), false);
91 verifyNoInteractions(listener1, listener2, listener3);
95 public void broadcastOnIssueChange_has_no_effect_when_no_changeEvent() {
96 underTest.broadcastOnIssueChange(oneIssueOnComponent1, emptySet(), false);
98 verifyNoInteractions(listener1, listener2, listener3);
102 public void broadcastOnIssueChange_passes_same_arguments_to_all_listeners_in_order_of_addition_to_constructor() {
103 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
105 ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor();
106 inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture());
107 Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue();
108 inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
109 inOrder.verify(listener3).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
110 inOrder.verifyNoMoreInteractions();
114 public void broadcastOnIssueChange_calls_all_listeners_even_if_one_throws_an_exception() {
115 QGChangeEventListener failingListener = new QGChangeEventListener[] {listener1, listener2, listener3}[new Random().nextInt(3)];
116 doThrow(new RuntimeException("Faking an exception thrown by onChanges"))
117 .when(failingListener)
118 .onIssueChanges(any(), any());
120 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
122 ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor();
123 inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture());
124 Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue();
125 inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
126 inOrder.verify(listener3).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
127 inOrder.verifyNoMoreInteractions();
129 assertThat(logTester.logs(Level.TRACE)).hasSizeGreaterThanOrEqualTo(3).contains(
130 format("calling onChange() on listener %s for events %s...", listener1.getClass().getName(), component1QGChangeEvent),
131 format("calling onChange() on listener %s for events %s...", listener2.getClass().getName(), component1QGChangeEvent),
132 format("calling onChange() on listener %s for events %s...", listener3.getClass().getName(), component1QGChangeEvent));
133 assertThat(logTester.logs(Level.WARN)).hasSizeGreaterThanOrEqualTo(1).contains(
134 format("onChange() call failed on listener %s for events %s", failingListener.getClass().getName(), component1QGChangeEvent));
139 public void broadcastOnIssueChange_stops_calling_listeners_when_one_throws_an_ERROR() {
140 doThrow(new Error("Faking an error thrown by a listener"))
142 .onIssueChanges(any(), any());
144 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
146 ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor();
147 inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture());
148 Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue();
149 inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues));
150 inOrder.verifyNoMoreInteractions();
151 assertThat(logTester.logs(Level.TRACE)).hasSizeGreaterThanOrEqualTo(2).contains(
152 format("calling onChange() on listener %s for events %s...", listener1.getClass().getName(), component1QGChangeEvent),
153 format("calling onChange() on listener %s for events %s...", listener2.getClass().getName(), component1QGChangeEvent));
154 assertThat(logTester.logs(Level.WARN)).hasSizeGreaterThanOrEqualTo(1).contains("Broadcasting to listeners failed for 1 events");
158 public void broadcastOnIssueChange_logs_each_listener_call_at_TRACE_level() {
159 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
161 assertThat(logTester.logs(Level.TRACE)).hasSizeGreaterThanOrEqualTo(3)
163 "calling onChange() on listener " + listener1.getClass().getName() + " for events " + component1QGChangeEvent + "...",
164 "calling onChange() on listener " + listener2.getClass().getName() + " for events " + component1QGChangeEvent + "...",
165 "calling onChange() on listener " + listener3.getClass().getName() + " for events " + component1QGChangeEvent + "...");
169 public void broadcastOnIssueChange_passes_immutable_set_of_ChangedIssues() {
170 QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(Set.of(listener1));
172 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
174 ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor();
175 inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture());
176 assertThat(changedIssuesCaptor.getValue()).isInstanceOf(ImmutableSet.class);
180 public void broadcastOnIssueChange_has_no_effect_when_no_listener() {
181 QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(Set.of());
183 underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false);
185 verifyNoInteractions(listener1, listener2, listener3);
189 public void broadcastOnIssueChange_calls_listener_for_each_component_uuid_with_at_least_one_QGChangeEvent() {
190 // branch has multiple issues
191 BranchDto component2 = newBranchDto(project1Uuid + "2");
192 DefaultIssue[] component2Issues = {newDefaultIssue(component2.getUuid()), newDefaultIssue(component2.getUuid())};
193 QGChangeEvent component2QGChangeEvent = newQGChangeEvent(component2);
195 // branch 3 has multiple QGChangeEvent and only one issue
196 BranchDto component3 = newBranchDto(project1Uuid + "3");
197 DefaultIssue component3Issue = newDefaultIssue(component3.getUuid());
198 QGChangeEvent[] component3QGChangeEvents = {newQGChangeEvent(component3), newQGChangeEvent(component3)};
200 // branch 4 has multiple QGChangeEvent and multiples issues
201 BranchDto component4 = newBranchDto(project1Uuid + "4");
202 DefaultIssue[] component4Issues = {newDefaultIssue(component4.getUuid()), newDefaultIssue(component4.getUuid())};
203 QGChangeEvent[] component4QGChangeEvents = {newQGChangeEvent(component4), newQGChangeEvent(component4)};
205 // branch 5 has no QGChangeEvent but one issue
206 BranchDto component5 = newBranchDto(project1Uuid + "5");
207 DefaultIssue component5Issue = newDefaultIssue(component5.getUuid());
209 List<DefaultIssue> issues = Stream.of(
210 Stream.of(component1Issue),
211 Arrays.stream(component2Issues),
212 Stream.of(component3Issue),
213 Arrays.stream(component4Issues),
214 Stream.of(component5Issue))
218 List<DefaultIssue> changedIssues = randomizedList(issues);
219 List<QGChangeEvent> qgChangeEvents = Stream.of(
220 Stream.of(component1QGChangeEvent),
221 Stream.of(component2QGChangeEvent),
222 Arrays.stream(component3QGChangeEvents),
223 Arrays.stream(component4QGChangeEvents))
227 underTest.broadcastOnIssueChange(changedIssues, randomizedList(qgChangeEvents), false);
229 listeners.forEach(listener -> {
230 verifyListenerCalled(listener, component1QGChangeEvent, component1Issue);
231 verifyListenerCalled(listener, component2QGChangeEvent, component2Issues);
232 Arrays.stream(component3QGChangeEvents)
233 .forEach(component3QGChangeEvent -> verifyListenerCalled(listener, component3QGChangeEvent, component3Issue));
234 Arrays.stream(component4QGChangeEvents)
235 .forEach(component4QGChangeEvent -> verifyListenerCalled(listener, component4QGChangeEvent, component4Issues));
237 verifyNoMoreInteractions(listener1, listener2, listener3);
241 public void isNotClosed_returns_true_if_issue_in_one_of_opened_states() {
242 DefaultIssue defaultIssue = new DefaultIssue();
243 defaultIssue.setStatus(Issue.STATUS_REOPENED);
244 defaultIssue.setKey("abc");
245 defaultIssue.setType(RuleType.BUG);
246 defaultIssue.setSeverity("BLOCKER");
248 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
250 assertThat(changedIssue.isNotClosed()).isTrue();
254 public void isNotClosed_returns_false_if_issue_in_one_of_closed_states() {
255 DefaultIssue defaultIssue = new DefaultIssue();
256 defaultIssue.setStatus(Issue.STATUS_CONFIRMED);
257 defaultIssue.setKey("abc");
258 defaultIssue.setType(RuleType.BUG);
259 defaultIssue.setSeverity("BLOCKER");
261 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
263 assertThat(changedIssue.isNotClosed()).isFalse();
267 public void isVulnerability_returns_true_if_issue_is_of_type_vulnerability() {
268 DefaultIssue defaultIssue = new DefaultIssue();
269 defaultIssue.setStatus(Issue.STATUS_OPEN);
270 defaultIssue.setType(RuleType.VULNERABILITY);
272 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
274 assertThat(changedIssue.isVulnerability()).isTrue();
278 public void isVulnerability_returns_false_if_issue_is_not_of_type_vulnerability() {
279 DefaultIssue defaultIssue = new DefaultIssue();
280 defaultIssue.setStatus(Issue.STATUS_OPEN);
281 defaultIssue.setType(RuleType.BUG);
283 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
285 assertThat(changedIssue.isVulnerability()).isFalse();
289 public void fromAlm_returns_false_by_default() {
290 DefaultIssue defaultIssue = new DefaultIssue();
291 defaultIssue.setStatus(Issue.STATUS_OPEN);
293 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
295 assertThat(changedIssue.fromAlm()).isFalse();
299 public void getSeverity_should_returns_default_issue_severity() {
300 DefaultIssue defaultIssue = new DefaultIssue();
301 defaultIssue.setStatus(Issue.STATUS_OPEN);
302 defaultIssue.setSeverity("BLOCKER");
304 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
306 assertThat(changedIssue.getSeverity()).isEqualTo(defaultIssue.severity());
310 public void test_ChangedIssueImpl_toString() {
311 DefaultIssue defaultIssue = new DefaultIssue();
312 defaultIssue.setStatus(Issue.STATUS_CONFIRMED);
313 defaultIssue.setKey("abc");
314 defaultIssue.setType(RuleType.BUG);
315 defaultIssue.setSeverity("BLOCKER");
316 String expected = "ChangedIssueImpl{key='abc', status=" + Issue.STATUS_CONFIRMED + ", type=" + RuleType.BUG + ", severity=BLOCKER, fromAlm=false}";
318 ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue);
320 assertThat(changedIssue).hasToString(expected);
324 public void test_status_mapping() {
325 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_OPEN))).isEqualTo(QGChangeEventListener.Status.OPEN);
326 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_REOPENED))).isEqualTo(QGChangeEventListener.Status.REOPENED);
327 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_CONFIRMED))).isEqualTo(QGChangeEventListener.Status.CONFIRMED);
328 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FALSE_POSITIVE)))
329 .isEqualTo(QGChangeEventListener.Status.RESOLVED_FP);
330 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_WONT_FIX)))
331 .isEqualTo(QGChangeEventListener.Status.RESOLVED_WF);
332 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FIXED)))
333 .isEqualTo(QGChangeEventListener.Status.RESOLVED_FIXED);
335 ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_CLOSED));
336 fail("Expected exception");
337 } catch (Exception e) {
338 assertThat(e).hasMessage("Unexpected status: CLOSED");
341 ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED));
342 fail("Expected exception");
343 } catch (Exception e) {
344 assertThat(e).hasMessage("A resolved issue should have a resolution");
347 ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_REMOVED));
348 fail("Expected exception");
349 } catch (Exception e) {
350 assertThat(e).hasMessage("Unexpected resolution for a resolved issue: REMOVED");
355 public void test_status_mapping_on_security_hotspots() {
356 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW)))
357 .isEqualTo(QGChangeEventListener.Status.TO_REVIEW);
358 assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED)))
359 .isEqualTo(QGChangeEventListener.Status.REVIEWED);
362 private void verifyListenerCalled(QGChangeEventListener listener, QGChangeEvent changeEvent, DefaultIssue... issues) {
363 ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor();
364 verify(listener).onIssueChanges(same(changeEvent), changedIssuesCaptor.capture());
365 Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue();
366 Tuple[] expected = Arrays.stream(issues)
367 .map(issue -> tuple(issue.key(), ChangedIssueImpl.statusOf(issue), issue.type()))
368 .toArray(Tuple[]::new);
369 assertThat(changedIssues)
370 .hasSize(issues.length)
371 .extracting(ChangedIssue::getKey, ChangedIssue::getStatus, ChangedIssue::getType)
372 .containsOnly(expected);
375 private static final String[] POSSIBLE_STATUSES = Stream.of(Issue.STATUS_CONFIRMED, Issue.STATUS_REOPENED, Issue.STATUS_RESOLVED).toArray(String[]::new);
376 private static int issueIdCounter = 0;
378 private static DefaultIssue newDefaultIssue(String projectUuid) {
379 DefaultIssue defaultIssue = new DefaultIssue();
380 defaultIssue.setKey("issue_" + issueIdCounter++);
381 defaultIssue.setProjectUuid(projectUuid);
382 defaultIssue.setType(RuleType.values()[new Random().nextInt(RuleType.values().length)]);
383 defaultIssue.setStatus(POSSIBLE_STATUSES[new Random().nextInt(POSSIBLE_STATUSES.length)]);
384 String[] possibleResolutions = possibleResolutions(defaultIssue.getStatus());
385 if (possibleResolutions.length > 0) {
386 defaultIssue.setResolution(possibleResolutions[new Random().nextInt(possibleResolutions.length)]);
391 private static String[] possibleResolutions(String status) {
392 if (Issue.STATUS_RESOLVED.equals(status)) {
393 return new String[]{Issue.RESOLUTION_FALSE_POSITIVE, Issue.RESOLUTION_WONT_FIX};
395 return new String[0];
398 private static BranchDto newBranchDto(String uuid) {
399 BranchDto branchDto = new BranchDto();
400 branchDto.setUuid(uuid);
404 private static QGChangeEvent newQGChangeEvent(BranchDto branch) {
405 QGChangeEvent res = mock(QGChangeEvent.class);
406 when(res.getBranch()).thenReturn(branch);
410 private static <T> ArgumentCaptor<Set<T>> newSetCaptor() {
411 Class<Set<T>> clazz = (Class<Set<T>>) (Class) Set.class;
412 return ArgumentCaptor.forClass(clazz);
415 private static <T> List<T> randomizedList(List<T> issues) {
416 ArrayList<T> res = new ArrayList<>(issues);
417 Collections.shuffle(res);
418 return ImmutableList.copyOf(res);