Search in sources :

Example 16 with ArgumentCaptor

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)));
    }
}
Also used : ArgumentCaptor(org.mockito.ArgumentCaptor) InputStream(java.io.InputStream) Test(org.junit.Test)

Example 17 with ArgumentCaptor

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));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) After(org.junit.After) BiConsumer(java.util.function.BiConsumer) Message(org.apache.qpid.proton.message.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Released(org.apache.qpid.proton.amqp.messaging.Released) Future(io.vertx.core.Future) Mockito(org.mockito.Mockito) Source(org.apache.qpid.proton.amqp.transport.Source) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) ProtonReceiver(io.vertx.proton.ProtonReceiver) Released(org.apache.qpid.proton.amqp.messaging.Released) ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Handler(io.vertx.core.Handler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Source(org.apache.qpid.proton.amqp.transport.Source) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Async(io.vertx.ext.unit.Async) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Test(org.junit.Test)

Example 18 with ArgumentCaptor

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));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) TestContext(io.vertx.ext.unit.TestContext) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RunWith(org.junit.runner.RunWith) ExpiringValueCache(org.eclipse.hono.cache.ExpiringValueCache) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) ArgumentCaptor(org.mockito.ArgumentCaptor) Duration(java.time.Duration) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Timeout(org.junit.rules.Timeout) SignatureAlgorithm(io.jsonwebtoken.SignatureAlgorithm) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) TriTuple(org.eclipse.hono.util.TriTuple) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) Date(java.sql.Date) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) Jwts(io.jsonwebtoken.Jwts) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Message(org.apache.qpid.proton.message.Message) ProtonDelivery(io.vertx.proton.ProtonDelivery) Async(io.vertx.ext.unit.Async) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) Duration(java.time.Duration) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Test(org.junit.Test)

Example 19 with ArgumentCaptor

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));
}
Also used : ProjectStatus(com.thoughtworks.go.domain.activity.ProjectStatus) ArgumentCaptor(org.mockito.ArgumentCaptor) Permissions(com.thoughtworks.go.config.security.Permissions) Test(org.junit.Test)

Example 20 with ArgumentCaptor

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()));
    }
}
Also used : PluggableTask(com.thoughtworks.go.config.pluggabletask.PluggableTask) ArgumentCaptor(org.mockito.ArgumentCaptor) DefaultGoPublisher(com.thoughtworks.go.work.DefaultGoPublisher) PluginConfiguration(com.thoughtworks.go.domain.config.PluginConfiguration) EnvironmentVariableContext(com.thoughtworks.go.util.command.EnvironmentVariableContext) PluggableTask(com.thoughtworks.go.config.pluggabletask.PluggableTask) CruiseControlException(com.thoughtworks.go.util.command.CruiseControlException) Test(org.junit.Test)

Aggregations

ArgumentCaptor (org.mockito.ArgumentCaptor)43 Test (org.junit.Test)22 Map (java.util.Map)18 Collections (java.util.Collections)17 List (java.util.List)16 Matchers.anyString (org.mockito.Matchers.anyString)15 Test (org.testng.annotations.Test)15 HashMap (java.util.HashMap)13 HashSet (java.util.HashSet)13 Set (java.util.Set)13 Collectors (java.util.stream.Collectors)13 Mockito.verify (org.mockito.Mockito.verify)13 Matchers.any (org.mockito.Matchers.any)12 Matchers.eq (org.mockito.Matchers.eq)12 Before (org.junit.Before)9 Mockito (org.mockito.Mockito)9 Context (io.vertx.core.Context)8 Handler (io.vertx.core.Handler)8 Vertx (io.vertx.core.Vertx)8 JsonObject (io.vertx.core.json.JsonObject)8