Search in sources :

Example 81 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class SendIssueNotificationsStepTest method send_new_issues_notification_to_user_only_for_those_assigned_to_her.

@Test
public void send_new_issues_notification_to_user_only_for_those_assigned_to_her() throws IOException {
    UserDto perceval = db.users().insertUser(u -> u.setLogin("perceval"));
    Integer[] assigned = IntStream.range(0, 5).mapToObj(i -> 10_000 * i).toArray(Integer[]::new);
    Duration expectedEffort = Duration.create(stream(assigned).mapToInt(i -> i).sum());
    UserDto arthur = db.users().insertUser(u -> u.setLogin("arthur"));
    Integer[] assignedToOther = IntStream.range(0, 3).mapToObj(i -> 10).toArray(Integer[]::new);
    List<DefaultIssue> issues = concat(stream(assigned).map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort)).setAssigneeUuid(perceval.getUuid()).setNew(true).setCreationDate(new Date(ANALYSE_DATE))), stream(assignedToOther).map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort)).setAssigneeUuid(arthur.getUuid()).setNew(true).setCreationDate(new Date(ANALYSE_DATE)))).collect(toList());
    shuffle(issues);
    ProtoIssueCache protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
    DiskCache.CacheAppender newIssueCache = protoIssueCache.newAppender();
    issues.forEach(newIssueCache::append);
    newIssueCache.close();
    analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
    when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
    NotificationFactory notificationFactory = mock(NotificationFactory.class);
    NewIssuesNotification newIssuesNotificationMock = createNewIssuesNotificationMock();
    when(notificationFactory.newNewIssuesNotification(assigneeCacheCaptor.capture())).thenReturn(newIssuesNotificationMock);
    MyNewIssuesNotification myNewIssuesNotificationMock1 = createMyNewIssuesNotificationMock();
    MyNewIssuesNotification myNewIssuesNotificationMock2 = createMyNewIssuesNotificationMock();
    doReturn(myNewIssuesNotificationMock1).doReturn(myNewIssuesNotificationMock2).when(notificationFactory).newMyNewIssuesNotification(any(assigneeCacheType));
    TestComputationStepContext context = new TestComputationStepContext();
    new SendIssueNotificationsStep(protoIssueCache, treeRootHolder, notificationService, analysisMetadataHolder, notificationFactory, db.getDbClient()).execute(context);
    verify(notificationService).deliverEmails(ImmutableSet.of(myNewIssuesNotificationMock1, myNewIssuesNotificationMock2));
    // old API compatibility
    verify(notificationService).deliver(myNewIssuesNotificationMock1);
    verify(notificationService).deliver(myNewIssuesNotificationMock2);
    verify(notificationFactory).newNewIssuesNotification(assigneeCacheCaptor.capture());
    verify(notificationFactory, times(2)).newMyNewIssuesNotification(assigneeCacheCaptor.capture());
    verifyNoMoreInteractions(notificationFactory);
    verifyAssigneeCache(assigneeCacheCaptor, perceval, arthur);
    Map<String, MyNewIssuesNotification> myNewIssuesNotificationMocksByUsersName = new HashMap<>();
    ArgumentCaptor<UserDto> userCaptor1 = forClass(UserDto.class);
    verify(myNewIssuesNotificationMock1).setAssignee(userCaptor1.capture());
    myNewIssuesNotificationMocksByUsersName.put(userCaptor1.getValue().getLogin(), myNewIssuesNotificationMock1);
    ArgumentCaptor<UserDto> userCaptor2 = forClass(UserDto.class);
    verify(myNewIssuesNotificationMock2).setAssignee(userCaptor2.capture());
    myNewIssuesNotificationMocksByUsersName.put(userCaptor2.getValue().getLogin(), myNewIssuesNotificationMock2);
    MyNewIssuesNotification myNewIssuesNotificationMock = myNewIssuesNotificationMocksByUsersName.get("perceval");
    ArgumentCaptor<NewIssuesStatistics.Stats> statsCaptor = forClass(NewIssuesStatistics.Stats.class);
    verify(myNewIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), statsCaptor.capture());
    verify(myNewIssuesNotificationMock).setDebt(expectedEffort);
    NewIssuesStatistics.Stats stats = statsCaptor.getValue();
    assertThat(stats.hasIssues()).isTrue();
    // just checking all issues have been added to the stats
    DistributedMetricStatsInt severity = stats.getDistributedMetricStats(NewIssuesStatistics.Metric.RULE_TYPE);
    assertThat(severity.getOnCurrentAnalysis()).isEqualTo(assigned.length);
    assertThat(severity.getTotal()).isEqualTo(assigned.length);
    verifyStatistics(context, 1, 2, 0);
}
Also used : Branch(org.sonar.ce.task.projectanalysis.analysis.Branch) Collections.shuffle(java.util.Collections.shuffle) NOTIF_TYPES(org.sonar.ce.task.projectanalysis.step.SendIssueNotificationsStep.NOTIF_TYPES) Duration(org.sonar.api.utils.Duration) NewIssuesNotification(org.sonar.server.issue.notification.NewIssuesNotification) RandomStringUtils.randomAlphanumeric(org.apache.commons.lang.RandomStringUtils.randomAlphanumeric) Date(java.util.Date) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) NewIssuesStatistics(org.sonar.server.issue.notification.NewIssuesStatistics) PULL_REQUEST(org.sonar.db.component.BranchType.PULL_REQUEST) ComputationStep(org.sonar.ce.task.step.ComputationStep) Collections.singleton(java.util.Collections.singleton) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) IssueTesting.newIssue(org.sonar.db.issue.IssueTesting.newIssue) Map(java.util.Map) AnalysisMetadataHolderRule(org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule) MyNewIssuesNotification(org.sonar.server.issue.notification.MyNewIssuesNotification) ReportComponent.builder(org.sonar.ce.task.projectanalysis.component.ReportComponent.builder) Mockito.doReturn(org.mockito.Mockito.doReturn) NotificationService(org.sonar.server.notification.NotificationService) ProtoIssueCache(org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache) DbTester(org.sonar.db.DbTester) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) System2(org.sonar.api.utils.System2) Notification(org.sonar.api.notifications.Notification) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) Set(java.util.Set) IssuesChangesNotification(org.sonar.server.issue.notification.IssuesChangesNotification) BRANCH(org.sonar.db.component.BranchType.BRANCH) List(java.util.List) ComponentDto(org.sonar.db.component.ComponentDto) Stream(java.util.stream.Stream) DistributedMetricStatsInt(org.sonar.server.issue.notification.DistributedMetricStatsInt) RuleKey(org.sonar.api.rule.RuleKey) TreeRootHolderRule(org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule) Mockito.any(org.mockito.Mockito.any) Arrays.stream(java.util.Arrays.stream) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) ComponentTesting.newBranchDto(org.sonar.db.component.ComponentTesting.newBranchDto) RuleDefinitionDto(org.sonar.db.rule.RuleDefinitionDto) UserDto(org.sonar.db.user.UserDto) ComponentTesting.newFileDto(org.sonar.db.component.ComponentTesting.newFileDto) HashMap(java.util.HashMap) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) ComponentTesting.newBranchComponent(org.sonar.db.component.ComponentTesting.newBranchComponent) Supplier(java.util.function.Supplier) RuleTesting.newRule(org.sonar.db.rule.RuleTesting.newRule) ArrayList(java.util.ArrayList) RuleType(org.sonar.api.rules.RuleType) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentCaptor(org.mockito.ArgumentCaptor) SECURITY_HOTSPOT(org.sonar.api.rules.RuleType.SECURITY_HOTSPOT) Stream.concat(java.util.stream.Stream.concat) DefaultBranchImpl(org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl) Before(org.junit.Before) Component(org.sonar.ce.task.projectanalysis.component.Component) Tuple(org.assertj.core.groups.Tuple) BranchType(org.sonar.db.component.BranchType) RandomUtils.nextInt(org.apache.commons.lang.math.RandomUtils.nextInt) DefaultIssue(org.sonar.core.issue.DefaultIssue) Type(org.sonar.ce.task.projectanalysis.component.Component.Type) IOException(java.io.IOException) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) DiskCache(org.sonar.ce.task.projectanalysis.util.cache.DiskCache) Mockito.verify(org.mockito.Mockito.verify) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) ComponentTesting.newPrivateProjectDto(org.sonar.db.component.ComponentTesting.newPrivateProjectDto) Collectors.toList(java.util.stream.Collectors.toList) Mockito.never(org.mockito.Mockito.never) Rule(org.junit.Rule) ArgumentCaptor.forClass(org.mockito.ArgumentCaptor.forClass) NotificationFactory(org.sonar.ce.task.projectanalysis.notification.NotificationFactory) TestComputationStepContext(org.sonar.ce.task.step.TestComputationStepContext) Tuple.tuple(org.assertj.core.groups.Tuple.tuple) TemporaryFolder(org.junit.rules.TemporaryFolder) Project(org.sonar.server.project.Project) ProtoIssueCache(org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache) HashMap(java.util.HashMap) NewIssuesStatistics(org.sonar.server.issue.notification.NewIssuesStatistics) UserDto(org.sonar.db.user.UserDto) NotificationFactory(org.sonar.ce.task.projectanalysis.notification.NotificationFactory) NewIssuesNotification(org.sonar.server.issue.notification.NewIssuesNotification) MyNewIssuesNotification(org.sonar.server.issue.notification.MyNewIssuesNotification) Duration(org.sonar.api.utils.Duration) DefaultIssue(org.sonar.core.issue.DefaultIssue) DiskCache(org.sonar.ce.task.projectanalysis.util.cache.DiskCache) TestComputationStepContext(org.sonar.ce.task.step.TestComputationStepContext) Date(java.util.Date) Project(org.sonar.server.project.Project) MyNewIssuesNotification(org.sonar.server.issue.notification.MyNewIssuesNotification) DistributedMetricStatsInt(org.sonar.server.issue.notification.DistributedMetricStatsInt) Test(org.junit.Test)

Example 82 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class FPOrWontFixNotificationHandlerTest method deliver_does_not_send_email_request_for_notifications_a_subscriber_is_the_changeAuthor_of.

@Test
@UseDataProvider("FPorWontFixResolution")
public void deliver_does_not_send_email_request_for_notifications_a_subscriber_is_the_changeAuthor_of(String newResolution) {
    Project project = newProject(randomAlphabetic(5));
    User subscriber1 = newUser("subscriber1");
    User subscriber2 = newUser("subscriber2");
    User subscriber3 = newUser("subscriber3");
    User otherChangeAuthor = newUser("otherChangeAuthor");
    // subscriber1 is the changeAuthor of some notifications with issues assigned to subscriber1 only
    Set<IssuesChangesNotificationBuilder> subscriber1Notifications = IntStream.range(0, 1 + new Random().nextInt(2)).mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)).collect(toSet()), newUserChange(subscriber1))).collect(toSet());
    // subscriber1 is the changeAuthor of some notifications with issues assigned to subscriber1 and subscriber2
    Set<IssuesChangesNotificationBuilder> subscriber1and2Notifications = IntStream.range(0, 1 + new Random().nextInt(2)).mapToObj(j -> new IssuesChangesNotificationBuilder(Stream.concat(randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)), randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber1))).collect(toSet()), newUserChange(subscriber1))).collect(toSet());
    // subscriber2 is the changeAuthor of some notifications with issues assigned to subscriber2 only
    Set<IssuesChangesNotificationBuilder> subscriber2Notifications = IntStream.range(0, 1 + new Random().nextInt(2)).mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)).collect(toSet()), newUserChange(subscriber2))).collect(toSet());
    // subscriber2 is the changeAuthor of some notifications with issues assigned to subscriber2 and subscriber 3
    Set<IssuesChangesNotificationBuilder> subscriber2And3Notifications = IntStream.range(0, 1 + new Random().nextInt(2)).mapToObj(j -> new IssuesChangesNotificationBuilder(Stream.concat(randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber2)), randomIssues(t -> t.setProject(project).setNewResolution(newResolution).setAssignee(subscriber3))).collect(toSet()), newUserChange(subscriber2))).collect(toSet());
    // subscriber3 is the changeAuthor of no notification
    // otherChangeAuthor has some notifications
    Set<IssuesChangesNotificationBuilder> otherChangeAuthorNotifications = IntStream.range(0, 1 + new Random().nextInt(2)).mapToObj(j -> new IssuesChangesNotificationBuilder(randomIssues(t -> t.setProject(project).setNewResolution(newResolution)).collect(toSet()), newUserChange(otherChangeAuthor))).collect(toSet());
    when(emailNotificationChannel.isActivated()).thenReturn(true);
    Set<String> subscriberLogins = ImmutableSet.of(subscriber1.getLogin(), subscriber2.getLogin(), subscriber3.getLogin());
    when(notificationManager.findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER)).thenReturn(subscriberLogins.stream().map(FPOrWontFixNotificationHandlerTest::emailRecipientOf).collect(toSet()));
    int deliveredCount = new Random().nextInt(200);
    when(emailNotificationChannel.deliverAll(anySet())).thenReturn(deliveredCount).thenThrow(new IllegalStateException("deliver should be called only once"));
    Set<IssuesChangesNotification> notifications = Stream.of(subscriber1Notifications.stream(), subscriber1and2Notifications.stream(), subscriber2Notifications.stream(), subscriber2And3Notifications.stream(), otherChangeAuthorNotifications.stream()).flatMap(t -> t).map(serializer::serialize).collect(toSet());
    reset(serializer);
    int deliver = underTest.deliver(notifications);
    assertThat(deliver).isEqualTo(deliveredCount);
    verify(notificationManager).findSubscribedEmailRecipients(DO_NOT_FIX_ISSUE_CHANGE_DISPATCHER_KEY, project.getKey(), ALL_MUST_HAVE_ROLE_USER);
    verifyNoMoreInteractions(notificationManager);
    verify(emailNotificationChannel).isActivated();
    ArgumentCaptor<Set<EmailDeliveryRequest>> captor = ArgumentCaptor.forClass(requestSetType);
    verify(emailNotificationChannel).deliverAll(captor.capture());
    verifyNoMoreInteractions(emailNotificationChannel);
    ListMultimap<String, EmailDeliveryRequest> requestsByRecipientEmail = captor.getValue().stream().collect(index(EmailDeliveryRequest::getRecipientEmail));
    assertThat(requestsByRecipientEmail.get(emailOf(subscriber1.getLogin()))).containsOnly(Stream.of(subscriber2Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution))), subscriber2And3Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution))), otherChangeAuthorNotifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber1, toFpOrWontFix(newResolution)))).flatMap(t -> t).toArray(EmailDeliveryRequest[]::new));
    assertThat(requestsByRecipientEmail.get(emailOf(subscriber2.getLogin()))).containsOnly(Stream.of(subscriber1Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution))), subscriber1and2Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution))), otherChangeAuthorNotifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber2, toFpOrWontFix(newResolution)))).flatMap(t -> t).toArray(EmailDeliveryRequest[]::new));
    assertThat(requestsByRecipientEmail.get(emailOf(subscriber3.getLogin()))).containsOnly(Stream.of(subscriber1Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))), subscriber1and2Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))), subscriber2Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))), subscriber2And3Notifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution))), otherChangeAuthorNotifications.stream().map(notif -> newEmailDeliveryRequest(notif, subscriber3, toFpOrWontFix(newResolution)))).flatMap(t -> t).toArray(EmailDeliveryRequest[]::new));
    assertThat(requestsByRecipientEmail.get(emailOf(otherChangeAuthor.getLogin()))).isEmpty();
}
Also used : IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) ALL_MUST_HAVE_ROLE_USER(org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER) ListMultimap(com.google.common.collect.ListMultimap) RESOLUTION_WONT_FIX(org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) Random(java.util.Random) Mockito.spy(org.mockito.Mockito.spy) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) FpOrWontFix(org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix) ArgumentCaptor(org.mockito.ArgumentCaptor) EmailDeliveryRequest(org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest) MoreCollectors.index(org.sonar.core.util.stream.MoreCollectors.index) Collections.singleton(java.util.Collections.singleton) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) RESOLUTION_FALSE_POSITIVE(org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE) ChangedIssue(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue) Assert.fail(org.junit.Assert.fail) NotificationManager(org.sonar.server.notification.NotificationManager) IssuesChangesNotificationBuilderTesting.newProject(org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newProject) Collectors.toSet(java.util.stream.Collectors.toSet) User(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User) ImmutableSet(com.google.common.collect.ImmutableSet) Project(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project) RandomStringUtils.randomAlphabetic(org.apache.commons.lang.RandomStringUtils.randomAlphabetic) UseDataProvider(com.tngtech.java.junit.dataprovider.UseDataProvider) Set(java.util.Set) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) UserChange(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange) PER_PROJECT_NOTIFICATION(org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule(org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newRandomNotAHotspotRule) Mockito(org.mockito.Mockito) Stream(java.util.stream.Stream) Issue(org.sonar.api.issue.Issue) GLOBAL_NOTIFICATION(org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION) Change(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change) NotificationDispatcherMetadata(org.sonar.server.notification.NotificationDispatcherMetadata) EmailNotificationChannel(org.sonar.server.notification.email.EmailNotificationChannel) Mockito.reset(org.mockito.Mockito.reset) Mockito.mock(org.mockito.Mockito.mock) User(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User) ArgumentMatchers.anySet(org.mockito.ArgumentMatchers.anySet) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) IssuesChangesNotificationBuilderTesting.newProject(org.sonar.server.issue.notification.IssuesChangesNotificationBuilderTesting.newProject) Project(org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project) Random(java.util.Random) EmailDeliveryRequest(org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest) Test(org.junit.Test) UseDataProvider(com.tngtech.java.junit.dataprovider.UseDataProvider)

Example 83 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class AsyncIssueIndexingImplTest method characteristics_are_defined.

@Test
public void characteristics_are_defined() {
    BranchDto dto = new BranchDto().setBranchType(BRANCH).setKey("branch_1").setUuid("branch_uuid1").setProjectUuid("project_uuid1");
    dbClient.branchDao().insert(dbTester.getSession(), dto);
    dbTester.commit();
    insertSnapshot("analysis_1", "project_uuid1", 1);
    BranchDto dto2 = new BranchDto().setBranchType(PULL_REQUEST).setKey("pr_1").setUuid("pr_uuid_1").setProjectUuid("project_uuid2");
    dbClient.branchDao().insert(dbTester.getSession(), dto2);
    dbTester.commit();
    insertSnapshot("analysis_2", "project_uuid2", 2);
    underTest.triggerOnIndexCreation();
    ArgumentCaptor<Collection<CeTaskSubmit>> captor = ArgumentCaptor.forClass(Collection.class);
    verify(ceQueue, times(1)).massSubmit(captor.capture());
    List<Collection<CeTaskSubmit>> captures = captor.getAllValues();
    assertThat(captures).hasSize(1);
    Collection<CeTaskSubmit> tasks = captures.get(0);
    assertThat(tasks).hasSize(2);
    assertThat(tasks).extracting(p -> p.getCharacteristics().get(BRANCH_TYPE_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.BRANCH_KEY), p -> p.getCharacteristics().get(CeTaskCharacteristicDto.PULL_REQUEST)).containsExactlyInAnyOrder(tuple("BRANCH", "branch_1", null), tuple("PULL_REQUEST", null, "pr_1"));
}
Also used : BranchDto(org.sonar.db.component.BranchDto) Arrays(java.util.Arrays) BRANCH_TYPE_KEY(org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY) STATUS_PROCESSED(org.sonar.db.component.SnapshotDto.STATUS_PROCESSED) REPORT(org.sonar.db.ce.CeTaskTypes.REPORT) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HashMap(java.util.HashMap) PULL_REQUEST(org.sonar.db.component.BranchType.PULL_REQUEST) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CeActivityDto(org.sonar.db.ce.CeActivityDto) ArgumentCaptor(org.mockito.ArgumentCaptor) Map(java.util.Map) BRANCH_ISSUE_SYNC(org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC) CeTaskCharacteristicDto(org.sonar.db.ce.CeTaskCharacteristicDto) Before(org.junit.Before) DbTester(org.sonar.db.DbTester) System2(org.sonar.api.utils.System2) Assertions.tuple(org.assertj.core.api.Assertions.tuple) Collection(java.util.Collection) UuidFactory(org.sonar.core.util.UuidFactory) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) BRANCH(org.sonar.db.component.BranchType.BRANCH) SequenceUuidFactory(org.sonar.core.util.SequenceUuidFactory) Mockito.verify(org.mockito.Mockito.verify) DbClient(org.sonar.db.DbClient) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) List(java.util.List) Rule(org.junit.Rule) LogTester(org.sonar.api.utils.log.LogTester) CeTaskSubmit(org.sonar.ce.queue.CeTaskSubmit) CeQueueDto(org.sonar.db.ce.CeQueueDto) Optional(java.util.Optional) Status(org.sonar.db.ce.CeActivityDto.Status) SnapshotDto(org.sonar.db.component.SnapshotDto) Assertions.assertThatCode(org.assertj.core.api.Assertions.assertThatCode) LoggerLevel(org.sonar.api.utils.log.LoggerLevel) CeQueue(org.sonar.ce.queue.CeQueue) Mockito.mock(org.mockito.Mockito.mock) BranchDto(org.sonar.db.component.BranchDto) Collection(java.util.Collection) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) CeTaskSubmit(org.sonar.ce.queue.CeTaskSubmit) Test(org.junit.Test)

Example 84 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class ValidateActionTest method github_validation_checks.

@Test
public void github_validation_checks() {
    AlmSettingDto almSetting = insertAlmSetting(db.almSettings().insertGitHubAlmSetting(settings -> settings.setClientId("clientId").setClientSecret("clientSecret")));
    when(encryption.isEncrypted(any())).thenReturn(false);
    ws.newRequest().setParam("key", almSetting.getKey()).execute();
    ArgumentCaptor<AlmSettingDto> almSettingDtoArgumentCaptor = ArgumentCaptor.forClass(AlmSettingDto.class);
    verify(githubGlobalSettingsValidator).validate(almSettingDtoArgumentCaptor.capture());
    assertThat(almSettingDtoArgumentCaptor.getAllValues()).hasSize(1);
    assertThat(almSettingDtoArgumentCaptor.getValue().getClientId()).isEqualTo(almSetting.getClientId());
    assertThat(almSettingDtoArgumentCaptor.getValue().getDecryptedClientSecret(encryption)).isEqualTo(almSetting.getDecryptedClientSecret(encryption));
    assertThat(almSettingDtoArgumentCaptor.getValue().getAlm()).isEqualTo(almSetting.getAlm());
    assertThat(almSettingDtoArgumentCaptor.getValue().getAppId()).isEqualTo(almSetting.getAppId());
}
Also used : AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ComponentFinder(org.sonar.server.component.ComponentFinder) Settings(org.sonar.api.config.internal.Settings) BeforeClass(org.junit.BeforeClass) UserDto(org.sonar.db.user.UserDto) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) GitlabGlobalSettingsValidator(org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator) MultipleAlmFeatureProvider(org.sonar.server.almsettings.MultipleAlmFeatureProvider) BitbucketServerSettingsValidator(org.sonar.alm.client.bitbucketserver.BitbucketServerSettingsValidator) ALM(org.sonar.db.alm.setting.ALM) GithubGlobalSettingsValidator(org.sonar.alm.client.github.GithubGlobalSettingsValidator) Mockito.doThrow(org.mockito.Mockito.doThrow) ArgumentCaptor(org.mockito.ArgumentCaptor) WebService(org.sonar.api.server.ws.WebService) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Encryption(org.sonar.api.config.internal.Encryption) ResourceTypes(org.sonar.api.resources.ResourceTypes) UserSessionRule(org.sonar.server.tester.UserSessionRule) DbTester(org.sonar.db.DbTester) BitbucketCloudRestClient(org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient) TestRequest(org.sonar.server.ws.TestRequest) Test(org.junit.Test) BitbucketCloudValidator(org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudValidator) Mockito.when(org.mockito.Mockito.when) WsActionTester(org.sonar.server.ws.WsActionTester) NotFoundException(org.sonar.server.exceptions.NotFoundException) Mockito.verify(org.mockito.Mockito.verify) Rule(org.junit.Rule) ForbiddenException(org.sonar.server.exceptions.ForbiddenException) AzureDevOpsValidator(org.sonar.alm.client.azure.AzureDevOpsValidator) Tuple.tuple(org.assertj.core.groups.Tuple.tuple) AzureDevOpsHttpClient(org.sonar.alm.client.azure.AzureDevOpsHttpClient) Mockito.mock(org.mockito.Mockito.mock) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) Test(org.junit.Test)

Example 85 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class ValidateActionTest method github_validation_checks_with_encrypted_secret.

@Test
public void github_validation_checks_with_encrypted_secret() {
    String secret = "encrypted-secret";
    String decryptedSecret = "decrypted-secret";
    AlmSettingDto almSetting = insertAlmSetting(db.almSettings().insertGitHubAlmSetting(settings -> settings.setClientId("clientId").setClientSecret(secret)));
    when(encryption.isEncrypted(secret)).thenReturn(true);
    when(encryption.decrypt(secret)).thenReturn(decryptedSecret);
    ws.newRequest().setParam("key", almSetting.getKey()).execute();
    ArgumentCaptor<AlmSettingDto> almSettingDtoArgumentCaptor = ArgumentCaptor.forClass(AlmSettingDto.class);
    verify(githubGlobalSettingsValidator).validate(almSettingDtoArgumentCaptor.capture());
    assertThat(almSettingDtoArgumentCaptor.getAllValues()).hasSize(1);
    assertThat(almSettingDtoArgumentCaptor.getValue().getClientId()).isEqualTo(almSetting.getClientId());
    assertThat(almSettingDtoArgumentCaptor.getValue().getDecryptedClientSecret(encryption)).isEqualTo(decryptedSecret);
    assertThat(almSettingDtoArgumentCaptor.getValue().getAlm()).isEqualTo(almSetting.getAlm());
    assertThat(almSettingDtoArgumentCaptor.getValue().getAppId()).isEqualTo(almSetting.getAppId());
}
Also used : AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ComponentFinder(org.sonar.server.component.ComponentFinder) Settings(org.sonar.api.config.internal.Settings) BeforeClass(org.junit.BeforeClass) UserDto(org.sonar.db.user.UserDto) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) GitlabGlobalSettingsValidator(org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator) MultipleAlmFeatureProvider(org.sonar.server.almsettings.MultipleAlmFeatureProvider) BitbucketServerSettingsValidator(org.sonar.alm.client.bitbucketserver.BitbucketServerSettingsValidator) ALM(org.sonar.db.alm.setting.ALM) GithubGlobalSettingsValidator(org.sonar.alm.client.github.GithubGlobalSettingsValidator) Mockito.doThrow(org.mockito.Mockito.doThrow) ArgumentCaptor(org.mockito.ArgumentCaptor) WebService(org.sonar.api.server.ws.WebService) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Encryption(org.sonar.api.config.internal.Encryption) ResourceTypes(org.sonar.api.resources.ResourceTypes) UserSessionRule(org.sonar.server.tester.UserSessionRule) DbTester(org.sonar.db.DbTester) BitbucketCloudRestClient(org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient) TestRequest(org.sonar.server.ws.TestRequest) Test(org.junit.Test) BitbucketCloudValidator(org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudValidator) Mockito.when(org.mockito.Mockito.when) WsActionTester(org.sonar.server.ws.WsActionTester) NotFoundException(org.sonar.server.exceptions.NotFoundException) Mockito.verify(org.mockito.Mockito.verify) Rule(org.junit.Rule) ForbiddenException(org.sonar.server.exceptions.ForbiddenException) AzureDevOpsValidator(org.sonar.alm.client.azure.AzureDevOpsValidator) Tuple.tuple(org.assertj.core.groups.Tuple.tuple) AzureDevOpsHttpClient(org.sonar.alm.client.azure.AzureDevOpsHttpClient) Mockito.mock(org.mockito.Mockito.mock) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) Test(org.junit.Test)

Aggregations

ArgumentCaptor (org.mockito.ArgumentCaptor)231 Mockito.verify (org.mockito.Mockito.verify)156 List (java.util.List)128 Test (org.junit.Test)116 Mockito.mock (org.mockito.Mockito.mock)113 Mockito.when (org.mockito.Mockito.when)100 Test (org.junit.jupiter.api.Test)86 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)85 Mockito (org.mockito.Mockito)85 Map (java.util.Map)76 BeforeEach (org.junit.jupiter.api.BeforeEach)72 Arrays (java.util.Arrays)69 Collectors (java.util.stream.Collectors)69 Collections (java.util.Collections)68 Before (org.junit.Before)65 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)64 Mockito.times (org.mockito.Mockito.times)64 ArrayList (java.util.ArrayList)60 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)60 Mockito.never (org.mockito.Mockito.never)58