use of org.mockito.ArgumentCaptor in project wikidata-query-rdf by wikimedia.
the class KafkaPollerUnitTest method topicSubscribe.
@Test
public void topicSubscribe() throws RetryableException {
Collection<String> topics = ImmutableList.of("topictest", "othertopic");
// Each topic gets 2 partitions
ArgumentCaptor<String> partitionArgs = ArgumentCaptor.forClass(String.class);
createTopicPartitions(2, partitionArgs);
// Capture args for assign
ArgumentCaptor<Collection<TopicPartition>> assignArgs = ArgumentCaptor.forClass((Class) Collection.class);
doNothing().when(consumer).assign(assignArgs.capture());
when(consumer.offsetsForTimes(any())).thenAnswer(i -> {
Map<TopicPartition, Long> map = i.getArgumentAt(0, Map.class);
// Check that timestamps are OK
map.forEach((k, v) -> assertThat(v).isEqualTo(START_TIME.toEpochMilli()));
Map<TopicPartition, OffsetAndTimestamp> out = Maps.newHashMapWithExpectedSize(map.size());
// Make offset 1 for first partition and nothing for second
map.forEach((k, v) -> out.put(k, k.partition() == 0 ? new OffsetAndTimestamp(1000, v) : null));
// Using forEach here because collect() can't handle nulls
return out;
});
// capture args for seek
ArgumentCaptor<TopicPartition> seekArgs = ArgumentCaptor.forClass(TopicPartition.class);
doNothing().when(consumer).seek(seekArgs.capture(), eq(1000L));
ArgumentCaptor<Collection<TopicPartition>> seekBeginningArgs = ArgumentCaptor.forClass((Class) Collection.class);
doNothing().when(consumer).seekToEnd(seekBeginningArgs.capture());
when(consumer.poll(anyLong())).thenReturn(EMPTY_CHANGES);
KafkaPoller poller = new KafkaPoller(consumer, uris, START_TIME, BATCH_SIZE, topics, new DummyKafkaOffsetsRepository(), true, new MetricRegistry());
Batch batch = poller.firstBatch();
// We get partitions for both topics
verify(consumer, times(2)).partitionsFor(any());
assertThat(partitionArgs.getAllValues()).contains("topictest", "othertopic");
// We assign to 4 topics - 2 topics x 2 partitions
verify(consumer, times(1)).assign(any());
assertThat(assignArgs.getValue()).hasSize(4);
// Calling seek on both topics, partition 0
verify(consumer, times(2)).seek(any(), anyLong());
assertThat(seekArgs.getAllValues()).extracting(topicPartition -> topicPartition.topic()).contains("topictest", "othertopic");
assertThat(seekArgs.getAllValues()).extracting(tp -> tp.partition()).hasSize(2).containsOnly(0);
// Calling seekToEnd on both topics, partition 1
verify(consumer, times(2)).seekToEnd(any());
Collection<String> sbTopics = seekBeginningArgs.getAllValues().stream().flatMap(c -> c.stream()).map(tp -> tp.topic()).collect(toList());
assertThat(sbTopics).hasSize(2).contains("topictest", "othertopic");
Collection<Integer> sbPartitions = seekBeginningArgs.getAllValues().stream().flatMap(c -> c.stream()).map(tp -> tp.partition()).distinct().collect(toList());
assertThat(sbPartitions).hasSize(1).contains(1);
verify(consumer, times(1)).offsetsForTimes(any());
}
use of org.mockito.ArgumentCaptor in project wikidata-query-rdf by wikimedia.
the class KafkaPollerUnitTest method storedOffsetsFromStorage.
@Test
public void storedOffsetsFromStorage() throws RetryableException {
// Scenario where all offsets are loaded from storage
Collection<String> topics = ImmutableList.of("topictest", "othertopic");
KafkaOffsetsRepository offsetsRepository = mock(KafkaOffsetsRepository.class);
createTopicPartitions(2);
// capture args for assign
ArgumentCaptor<Collection<TopicPartition>> assignArgs = ArgumentCaptor.forClass((Class) Collection.class);
doNothing().when(consumer).assign(assignArgs.capture());
// capture args for seek
ArgumentCaptor<TopicPartition> seekTopics = ArgumentCaptor.forClass(TopicPartition.class);
ArgumentCaptor<Long> seekOffsets = ArgumentCaptor.forClass(Long.class);
doNothing().when(consumer).seek(seekTopics.capture(), seekOffsets.capture());
Map<TopicPartition, OffsetAndTimestamp> offsetMap = ImmutableMap.of(new TopicPartition("topictest", 0), new OffsetAndTimestamp(1, START_TIME.toEpochMilli()), new TopicPartition("topictest", 1), new OffsetAndTimestamp(2, START_TIME.toEpochMilli()), new TopicPartition("othertopic", 0), new OffsetAndTimestamp(3, START_TIME.toEpochMilli()), new TopicPartition("othertopic", 1), new OffsetAndTimestamp(4, START_TIME.toEpochMilli()));
when(offsetsRepository.load(any())).thenReturn(offsetMap);
when(consumer.poll(anyLong())).thenReturn(EMPTY_CHANGES);
KafkaPoller poller = new KafkaPoller(consumer, uris, START_TIME, BATCH_SIZE, topics, offsetsRepository, false, new MetricRegistry());
Batch batch = poller.firstBatch();
// should not call offsetsForTimes, since all offsets are in store
verify(consumer, times(0)).offsetsForTimes(any());
// We assign to 4 topics - 2 topics x 2 partitions
verify(consumer, times(1)).assign(any());
assertThat(assignArgs.getValue()).hasSize(4);
// Verify topics and offsets
assertThat(seekTopics.getAllValues()).containsExactlyInAnyOrderElementsOf(offsetMap.keySet());
List<Long> offsets = offsetMap.values().stream().map(o -> o.offset()).collect(toList());
assertThat(seekOffsets.getAllValues()).containsExactlyInAnyOrderElementsOf(offsets);
}
use of org.mockito.ArgumentCaptor in project hono by eclipse.
the class ConnectionFactoryImplTest method testConnectIgnoresSuccessfulOpenAfterTimeout.
/**
* Verifies that a connection attempt is failed if there is a timeout opening the connection
* and verifies that a subsequently received 'open' frame is ignored.
*
* @param ctx The vert.x test context.
*/
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectIgnoresSuccessfulOpenAfterTimeout(final VertxTestContext ctx) {
final long connectTimeout = 200L;
// GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
props.setConnectTimeout((int) connectTimeout);
final AtomicReference<Handler<Long>> timeoutHandlerRef = new AtomicReference<>();
when(vertx.setTimer(eq(connectTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
timeoutHandlerRef.set(invocation.getArgument(1));
return 1L;
});
final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
final ProtonClient protonClientMock = mock(ProtonClient.class);
final ProtonConnection protonConnectionMock = mock(ProtonConnection.class, Mockito.RETURNS_SELF);
doAnswer(invocation -> {
final Handler<AsyncResult<ProtonConnection>> resultHandler = invocation.getArgument(5);
resultHandler.handle(Future.succeededFuture(protonConnectionMock));
return null;
}).when(protonClientMock).connect(any(ProtonClientOptions.class), any(), anyInt(), any(), any(), VertxMockSupport.anyHandler());
factory.setProtonClient(protonClientMock);
// WHEN trying to connect to the server
factory.connect(null, null, null, ctx.failing(t -> {
// THEN the connection attempt fails with a TimeoutException and the given handler is invoked
ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandlerCaptor = VertxMockSupport.argumentCaptorHandler();
verify(protonConnectionMock).openHandler(openHandlerCaptor.capture());
// trigger timeout
timeoutHandlerRef.get().handle(1L);
// call openHandler - that will be too late for the connect invocation to succeed
openHandlerCaptor.getValue().handle(Future.succeededFuture(protonConnectionMock));
// and the connection will be disconnected
verify(protonConnectionMock).disconnect();
}
use of org.mockito.ArgumentCaptor in project hono by eclipse.
the class ConnectionFactoryImplTest method testConnectIgnoresFailedOpenAfterTimeout.
/**
* Verifies that a connection attempt is failed if there is a timeout opening the connection
* and verifies that a subsequently triggered failed open handler is ignored.
*
* @param ctx The vert.x test context.
*/
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectIgnoresFailedOpenAfterTimeout(final VertxTestContext ctx) {
final long connectTimeout = 200L;
// GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
props.setConnectTimeout((int) connectTimeout);
final AtomicReference<Handler<Long>> timeoutHandlerRef = new AtomicReference<>();
when(vertx.setTimer(eq(connectTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
timeoutHandlerRef.set(invocation.getArgument(1));
return 1L;
});
final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
final ProtonClient protonClientMock = mock(ProtonClient.class);
final ProtonConnection protonConnectionMock = mock(ProtonConnection.class, Mockito.RETURNS_SELF);
doAnswer(invocation -> {
final Handler<AsyncResult<ProtonConnection>> resultHandler = invocation.getArgument(5);
resultHandler.handle(Future.succeededFuture(protonConnectionMock));
return null;
}).when(protonClientMock).connect(any(ProtonClientOptions.class), any(), anyInt(), any(), any(), VertxMockSupport.anyHandler());
factory.setProtonClient(protonClientMock);
// WHEN trying to connect to the server
factory.connect(null, null, null, ctx.failing(t -> {
// THEN the connection attempt fails with a TimeoutException and the given handler is invoked
ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandlerCaptor = VertxMockSupport.argumentCaptorHandler();
verify(protonConnectionMock).openHandler(openHandlerCaptor.capture());
// trigger timeout
timeoutHandlerRef.get().handle(1L);
// call openHandler - that will be too late for the connect invocation to succeed
openHandlerCaptor.getValue().handle(Future.failedFuture("amqp:resource-limit-exceeded -connection disallowed by local policy"));
// and the connection will be disconnected
verify(protonConnectionMock).disconnect();
}
use of org.mockito.ArgumentCaptor in project hono by eclipse.
the class EdgeDeviceAutoProvisionerTest method verifySuccessfulAutoProvisioning.
@SuppressWarnings("unchecked")
private void verifySuccessfulAutoProvisioning() {
final ArgumentCaptor<Device> registeredDeviceArgumentCaptor = ArgumentCaptor.forClass(Device.class);
verify(deviceManagementService).createDevice(eq(Constants.DEFAULT_TENANT), eq(Optional.of(DEVICE_ID)), registeredDeviceArgumentCaptor.capture(), any());
final Device registeredDevice = registeredDeviceArgumentCaptor.getValue();
assertThat(registeredDevice).isEqualTo(NEW_EDGE_DEVICE);
final ArgumentCaptor<Map<String, Object>> messageArgumentCaptor = ArgumentCaptor.forClass(Map.class);
verify(sender).sendEvent(argThat(tenant -> tenant.getTenantId().equals(Constants.DEFAULT_TENANT)), argThat(assertion -> assertion.getDeviceId().equals(DEVICE_ID)), eq(EventConstants.CONTENT_TYPE_DEVICE_PROVISIONING_NOTIFICATION), any(), messageArgumentCaptor.capture(), any());
verify(deviceManagementService).updateDevice(eq(Constants.DEFAULT_TENANT), eq(DEVICE_ID), argThat(device -> device.getStatus().isAutoProvisioningNotificationSent()), any(Optional.class), any(Span.class));
final Map<String, Object> applicationProperties = messageArgumentCaptor.getValue();
verifyApplicationProperties(GATEWAY_ID, DEVICE_ID, applicationProperties);
}
Aggregations