use of org.mockito.ArgumentCaptor in project spring-security by spring-projects.
the class SwitchUserWebFilterTests method switchUser.
@Test
public void switchUser() {
final String targetUsername = "TEST_USERNAME";
final UserDetails switchUserDetails = switchUserDetails(targetUsername, true);
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("principal", "credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
verify(this.userDetailsService).findByUsername(targetUsername);
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication switchUserAuthentication = authenticationCaptor.getValue();
assertThat(switchUserAuthentication).isSameAs(savedSecurityContext.getAuthentication());
assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR));
assertThat(switchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)).contains(originalAuthentication.getName());
}
use of org.mockito.ArgumentCaptor in project spring-security by spring-projects.
the class SwitchUserWebFilterTests method switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain.
@Test
public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() {
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
final String targetUsername = "newSwitchPrincipal";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails(targetUsername, true)));
this.switchUserWebFilter.filter(exchange, chain).subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue();
assertThat(secondSwitchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(secondSwitchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName).findFirst().orElse(null)).isEqualTo(originalAuthentication.getName());
}
use of org.mockito.ArgumentCaptor in project storm by apache.
the class KafkaSpoutEmitTest method testSpoutWillSkipPartitionsAtTheMaxUncommittedOffsetsLimit.
@Test
public void testSpoutWillSkipPartitionsAtTheMaxUncommittedOffsetsLimit() {
// This verifies that partitions can't prevent each other from retrying tuples due to the maxUncommittedOffsets limit.
try (SimulatedTime simulatedTime = new SimulatedTime()) {
TopicPartition partitionTwo = new TopicPartition(SingleTopicKafkaSpoutConfiguration.TOPIC, 2);
KafkaSpout<String, String> spout = SpoutWithMockedConsumerSetupHelper.setupSpout(spoutConfig, conf, contextMock, collectorMock, consumerMock, partition, partitionTwo);
Map<TopicPartition, List<ConsumerRecord<String, String>>> records = new HashMap<>();
// This is cheating a bit since maxPollRecords would normally spread this across multiple polls
records.put(partition, SpoutWithMockedConsumerSetupHelper.createRecords(partition, 0, spoutConfig.getMaxUncommittedOffsets()));
records.put(partitionTwo, SpoutWithMockedConsumerSetupHelper.createRecords(partitionTwo, 0, spoutConfig.getMaxUncommittedOffsets() + 1));
int numMessages = spoutConfig.getMaxUncommittedOffsets() * 2 + 1;
when(consumerMock.poll(anyLong())).thenReturn(new ConsumerRecords<>(records));
for (int i = 0; i < numMessages; i++) {
spout.nextTuple();
}
ArgumentCaptor<KafkaSpoutMessageId> messageIds = ArgumentCaptor.forClass(KafkaSpoutMessageId.class);
verify(collectorMock, times(numMessages)).emit(anyString(), anyList(), messageIds.capture());
// Now fail a tuple on partition one and verify that it is allowed to retry, because the failed tuple is below the maxUncommittedOffsets limit
Optional<KafkaSpoutMessageId> failedMessageIdPartitionOne = messageIds.getAllValues().stream().filter(messageId -> messageId.partition() == partition.partition()).findAny();
spout.fail(failedMessageIdPartitionOne.get());
// Also fail the last tuple from partition two. Since the failed tuple is beyond the maxUncommittedOffsets limit, it should not be retried until earlier messages are acked.
Optional<KafkaSpoutMessageId> failedMessagePartitionTwo = messageIds.getAllValues().stream().filter(messageId -> messageId.partition() == partitionTwo.partition()).max((msgId, msgId2) -> (int) (msgId.offset() - msgId2.offset()));
spout.fail(failedMessagePartitionTwo.get());
reset(collectorMock);
Time.advanceTime(50);
when(consumerMock.poll(anyLong())).thenReturn(new ConsumerRecords<>(Collections.singletonMap(partition, SpoutWithMockedConsumerSetupHelper.createRecords(partition, failedMessageIdPartitionOne.get().offset(), 1))));
spout.nextTuple();
verify(collectorMock, times(1)).emit(anyObject(), anyObject(), anyObject());
InOrder inOrder = inOrder(consumerMock);
inOrder.verify(consumerMock).seek(partition, failedMessageIdPartitionOne.get().offset());
// Should not seek on the paused partition
inOrder.verify(consumerMock, never()).seek(eq(partitionTwo), anyLong());
inOrder.verify(consumerMock).pause(Collections.singleton(partitionTwo));
inOrder.verify(consumerMock).poll(anyLong());
inOrder.verify(consumerMock).resume(Collections.singleton(partitionTwo));
reset(collectorMock);
// Now also check that no more tuples are polled for, since both partitions are at their limits
spout.nextTuple();
verify(collectorMock, never()).emit(anyObject(), anyObject(), anyObject());
}
}
use of org.mockito.ArgumentCaptor in project storm by apache.
the class ProcessorBoltTest method testEmitAndAck.
@Test
public void testEmitAndAck() throws Exception {
setUpProcessorBolt(new FilterProcessor<Integer>(x -> true));
bolt.execute(mockTuple1);
ArgumentCaptor<Collection> anchor = ArgumentCaptor.forClass(Collection.class);
ArgumentCaptor<Values> values = ArgumentCaptor.forClass(Values.class);
ArgumentCaptor<String> os = ArgumentCaptor.forClass(String.class);
Mockito.verify(mockOutputCollector).emit(os.capture(), anchor.capture(), values.capture());
assertEquals("outputstream", os.getValue());
assertArrayEquals(new Object[] { mockTuple1 }, anchor.getValue().toArray());
assertEquals(new Values(100), values.getValue());
Mockito.verify(mockOutputCollector, Mockito.times(1)).ack(mockTuple1);
}
use of org.mockito.ArgumentCaptor in project dropwizard by dropwizard.
the class HealthCheckManagerTest method shouldNotChangeServerStateWhenNonCriticalHealthCheckRecovers.
@Test
void shouldNotChangeServerStateWhenNonCriticalHealthCheckRecovers() {
final List<HealthCheckConfiguration> configs = new ArrayList<>();
final HealthCheckConfiguration nonCriticalConfig = new HealthCheckConfiguration();
nonCriticalConfig.setName(NAME);
nonCriticalConfig.setCritical(false);
nonCriticalConfig.setSchedule(new Schedule());
configs.add(nonCriticalConfig);
final HealthCheckConfiguration criticalConfig = new HealthCheckConfiguration();
criticalConfig.setName(NAME_2);
criticalConfig.setCritical(true);
criticalConfig.setSchedule(new Schedule());
configs.add(criticalConfig);
final HealthCheckManager manager = new HealthCheckManager(unmodifiableList(configs), scheduler, new MetricRegistry(), SHUTDOWN_WAIT, true, Collections.emptyList());
final HealthCheck check = mock(HealthCheck.class);
manager.onHealthCheckAdded(NAME, check);
manager.onHealthCheckAdded(NAME_2, check);
manager.onStateChanged(NAME, false);
manager.onStateChanged(NAME_2, false);
assertThat(manager.isHealthy()).isFalse();
manager.onStateChanged(NAME, true);
assertThat(manager.isHealthy()).isFalse();
ArgumentCaptor<ScheduledHealthCheck> checkCaptor = ArgumentCaptor.forClass(ScheduledHealthCheck.class);
ArgumentCaptor<Boolean> healthyCaptor = ArgumentCaptor.forClass(Boolean.class);
verify(scheduler, times(2)).scheduleInitial(checkCaptor.capture());
verify(scheduler, times(3)).schedule(checkCaptor.capture(), healthyCaptor.capture());
assertThat(checkCaptor.getAllValues()).hasSize(5).satisfies(values -> assertThat(values).element(0).satisfies(value -> assertThat(value.getName()).isEqualTo(NAME)).satisfies(value -> assertThat(value.isCritical()).isFalse())).satisfies(values -> assertThat(values).element(1).satisfies(value -> assertThat(value.getName()).isEqualTo(NAME_2)).satisfies(value -> assertThat(value.isCritical()).isTrue())).satisfies(values -> assertThat(values).element(2).satisfies(value -> assertThat(value.getName()).isEqualTo(NAME)).satisfies(value -> assertThat(value.isCritical()).isFalse())).satisfies(values -> assertThat(values).element(3).satisfies(value -> assertThat(value.getName()).isEqualTo(NAME_2)).satisfies(value -> assertThat(value.isCritical()).isTrue())).satisfies(values -> assertThat(values).element(4).satisfies(value -> assertThat(value.getName()).isEqualTo(NAME)).satisfies(value -> assertThat(value.isCritical()).isFalse()));
assertThat(healthyCaptor.getAllValues()).containsExactly(false, false, true);
}
Aggregations