use of org.mockito.ArgumentCaptor in project hippo by NHS-digital-website.
the class S3ConnectorImplTest method abortsS3MultipartUploadRequest_onChunkUploadFailure.
@Test
public void abortsS3MultipartUploadRequest_onChunkUploadFailure() throws Exception {
// given
final String contentType = newRandomString();
final String uploadId = newRandomString();
given(s3ObjectKeyGenerator.generateObjectKey(fileName)).willReturn(objectKey);
final InitiateMultipartUploadResult result = mock(InitiateMultipartUploadResult.class);
given(result.getUploadId()).willReturn(uploadId);
given(s3.initiateMultipartUpload(any())).willReturn(result);
final InputStream uploadedFileInputStream = mock(InputStream.class);
final RuntimeException expectedCauseException = new RuntimeException(newRandomString());
given(s3.uploadPart(any(UploadPartRequest.class))).willThrow(expectedCauseException);
try {
// when
s3Connector.uploadFile(uploadedFileInputStream, fileName, contentType);
// then
fail("Exception was expected but none has been thrown.");
} catch (final RuntimeException actualException) {
// assert upload request - abort
final ArgumentCaptor<AbortMultipartUploadRequest> abortMultipartUploadRequestArgumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
then(s3).should().abortMultipartUpload(abortMultipartUploadRequestArgumentCaptor.capture());
final AbortMultipartUploadRequest actualAbortRequest = abortMultipartUploadRequestArgumentCaptor.getValue();
assertThat("Request aborted with correct bucket name", actualAbortRequest.getBucketName(), is(bucketName));
assertThat("Request aborted with correct object key", actualAbortRequest.getKey(), is(objectKey));
assertThat("Request aborted with correct upload id", actualAbortRequest.getUploadId(), is(uploadId));
// assert upload request - exception
assertThat("Exception is thrown with correct message.", actualException.getMessage(), is("Failed to upload file " + objectKey));
assertThat("Exception is thrown with correct cause.", actualException.getCause(), is(sameInstance(expectedCauseException)));
}
}
use of org.mockito.ArgumentCaptor in project hono by eclipse.
the class EventConsumerImplTest method testCreateRegistersBiConsumerAsMessageHandler.
/**
* Verifies that the message delivery for a received event is forwarded to the
* registered event consumer.
*
* @param ctx The test context.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCreateRegistersBiConsumerAsMessageHandler(final TestContext ctx) {
// GIVEN an event consumer that releases all messages
final Async consumerCreation = ctx.async();
final BiConsumer<ProtonDelivery, Message> eventConsumer = (delivery, message) -> {
ProtonHelper.released(delivery, true);
};
final RecordImpl attachments = new RecordImpl();
final Source source = mock(Source.class);
when(source.toString()).thenReturn("event/tenant");
final ProtonReceiver receiver = mock(ProtonReceiver.class);
when(receiver.getSource()).thenReturn(source);
when(receiver.attachments()).thenReturn(attachments);
when(receiver.getRemoteQoS()).thenReturn(ProtonQoS.AT_LEAST_ONCE);
when(receiver.open()).then(answer -> {
consumerCreation.complete();
return receiver;
});
final ProtonConnection con = mock(ProtonConnection.class);
when(con.createReceiver(anyString())).thenReturn(receiver);
when(receiver.openHandler(any(Handler.class))).thenAnswer(invocation -> {
final Handler handler = invocation.getArgument(0);
handler.handle(Future.succeededFuture(receiver));
return receiver;
});
final ArgumentCaptor<ProtonMessageHandler> messageHandler = ArgumentCaptor.forClass(ProtonMessageHandler.class);
EventConsumerImpl.create(vertx.getOrCreateContext(), new ClientConfigProperties(), con, "tenant", eventConsumer, open -> {
}, remoteDetach -> {
});
consumerCreation.await();
verify(receiver).handler(messageHandler.capture());
// WHEN an event is received
final ProtonDelivery delivery = mock(ProtonDelivery.class);
final Message msg = mock(Message.class);
messageHandler.getValue().handle(delivery, msg);
// THEN the message is released and settled
verify(delivery).disposition(any(Released.class), eq(Boolean.TRUE));
}
use of org.mockito.ArgumentCaptor in project hono by eclipse.
the class RegistrationClientImplTest method testAssertRegistrationAddsResponseToCacheOnCacheMiss.
/**
* Verifies that on a cache miss the adapter retrieves registration information
* from the Device Registration service and puts it to the cache.
*
* @param ctx The vert.x test context.
*/
@SuppressWarnings("unchecked")
@Test
public void testAssertRegistrationAddsResponseToCacheOnCacheMiss(final TestContext ctx) {
// GIVEN an adapter with an empty cache
client.setResponseCache(cache);
// WHEN getting registration information
final Async assertion = ctx.async();
client.assertRegistration("device").setHandler(ctx.asyncAssertSuccess(result -> assertion.complete()));
final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(sender).send(messageCaptor.capture(), any(Handler.class));
final JsonObject registrationAssertion = newRegistrationAssertionResult();
final Message response = ProtonHelper.message(registrationAssertion.encode());
MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
response.setCorrelationId(messageCaptor.getValue().getMessageId());
final ProtonDelivery delivery = mock(ProtonDelivery.class);
client.handleResponse(delivery, response);
// THEN the registration information has been added to the cache
verify(cache).put(eq(TriTuple.of("assert", "device", null)), any(RegistrationResult.class), any(Duration.class));
}
use of org.mockito.ArgumentCaptor in project gocd by gocd.
the class CcTrayConfigChangeHandlerTest method shouldUpdateCacheWithAppropriateViewersForProjectStatusWhenPipelineConfigChanges.
@Test
public void shouldUpdateCacheWithAppropriateViewersForProjectStatusWhenPipelineConfigChanges() {
String pipeline1Stage = "pipeline1 :: stage1";
String pipeline1job = "pipeline1 :: stage1 :: job1";
ProjectStatus statusOfPipeline1StageInCache = new ProjectStatus(pipeline1Stage, "OldActivity", "OldStatus", "OldLabel", new Date(), "p1-stage-url");
ProjectStatus statusOfPipeline1JobInCache = new ProjectStatus(pipeline1job, "OldActivity-Job", "OldStatus-Job", "OldLabel-Job", new Date(), "p1-job-url");
when(cache.get(pipeline1Stage)).thenReturn(statusOfPipeline1StageInCache);
when(cache.get(pipeline1job)).thenReturn(statusOfPipeline1JobInCache);
PipelineConfig pipeline1Config = GoConfigMother.pipelineHavingJob("pipeline1", "stage1", "job1", "arts", "dir").pipelineConfigByName(new CaseInsensitiveString("pipeline1"));
when(pipelinePermissionsAuthority.permissionsForPipeline(pipeline1Config.name())).thenReturn(new Permissions(viewers("user1", "user2"), null, null, null));
handler.call(pipeline1Config);
ArgumentCaptor<ArrayList<ProjectStatus>> argumentCaptor = new ArgumentCaptor<>();
verify(cache).putAll(argumentCaptor.capture());
List<ProjectStatus> allValues = argumentCaptor.getValue();
assertThat(allValues.get(0).name(), is(pipeline1Stage));
assertThat(allValues.get(0).viewers().contains("user1"), is(true));
assertThat(allValues.get(0).viewers().contains("user2"), is(true));
assertThat(allValues.get(0).viewers().contains("user3"), is(false));
assertThat(allValues.get(1).name(), is(pipeline1job));
assertThat(allValues.get(1).viewers().contains("user1"), is(true));
assertThat(allValues.get(1).viewers().contains("user2"), is(true));
assertThat(allValues.get(1).viewers().contains("user3"), is(false));
}
use of org.mockito.ArgumentCaptor in project gocd by gocd.
the class PluggableTaskBuilderTest method shouldPublishErrorMessageIfPluginThrowsAnException.
@Test
public void shouldPublishErrorMessageIfPluginThrowsAnException() throws CruiseControlException {
PluggableTask task = mock(PluggableTask.class);
when(task.getPluginConfiguration()).thenReturn(new PluginConfiguration());
PluggableTaskBuilder taskBuilder = new PluggableTaskBuilder(runIfConfigs, cancelBuilder, pluggableTask, TEST_PLUGIN_ID, "test-directory") {
@Override
protected ExecutionResult executeTask(Task task, DefaultGoPublisher publisher, EnvironmentVariableContext environmentVariableContext, String consoleLogCharset) {
throw new RuntimeException("err");
}
};
try {
taskBuilder.build(goPublisher, variableContext, taskExtension, null, null, "utf-8");
fail("expected exception to be thrown");
} catch (Exception e) {
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(goPublisher).taggedConsumeLine(eq(DefaultGoPublisher.ERR), captor.capture());
String error = "Error: err";
assertThat(captor.getValue(), is(error));
assertThat(e.getMessage(), is(new RuntimeException("err").toString()));
}
}
Aggregations