Search in sources :

Example 41 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class AmqpUploadTestBase method testAdapterRejectsBadInboundMessage.

/**
 * Verifies that a message containing a payload which has the <em>empty notification</em>
 * content type is rejected by the adapter.
 *
 * @param context The Vert.x context for running asynchronous tests.
 * @throws InterruptedException if test is interrupted while running.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAdapterRejectsBadInboundMessage(final VertxTestContext context) throws InterruptedException {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final VertxTestContext setup = new VertxTestContext();
    setupProtocolAdapter(tenantId, new Tenant(), deviceId, ProtonQoS.AT_LEAST_ONCE).map(s -> {
        setup.verify(() -> {
            final UnsignedLong maxMessageSize = s.getRemoteMaxMessageSize();
            assertWithMessage("max-message-size included in adapter's attach frame").that(maxMessageSize).isNotNull();
            assertWithMessage("max-message-size").that(maxMessageSize.longValue()).isGreaterThan(0);
        });
        sender = s;
        return s;
    }).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        context.failNow(setup.causeOfFailure());
        return;
    }
    final Message msg = ProtonHelper.message("some payload");
    msg.setContentType(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    msg.setAddress(getEndpointName());
    sender.send(msg, delivery -> {
        context.verify(() -> {
            assertThat(delivery.getRemoteState()).isInstanceOf(Rejected.class);
            final Rejected rejected = (Rejected) delivery.getRemoteState();
            final ErrorCondition error = rejected.getError();
            assertThat((Object) error.getCondition()).isEqualTo(Constants.AMQP_BAD_REQUEST);
        });
        context.completeNow();
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Symbol(org.apache.qpid.proton.amqp.Symbol) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) Binary(org.apache.qpid.proton.amqp.Binary) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Data(org.apache.qpid.proton.amqp.messaging.Data) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) LinkError(org.apache.qpid.proton.amqp.transport.LinkError) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Buffer(io.vertx.core.buffer.Buffer) Assertions(org.junit.jupiter.api.Assertions) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) Tenant(org.eclipse.hono.service.management.tenant.Tenant) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Message(org.apache.qpid.proton.message.Message) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) VertxTestContext(io.vertx.junit5.VertxTestContext) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Example 42 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class AmqpUploadTestBase method testAutoProvisioningViaGateway.

/**
 * Verifies that an edge device is auto-provisioned if it connects via a gateway equipped with the corresponding
 * authority.
 *
 * @param ctx The Vert.x test context.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAutoProvisioningViaGateway(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device gateway = new Device().setAuthorities(Collections.singleton(RegistryManagementConstants.AUTHORITY_AUTO_PROVISIONING_ENABLED));
    final String username = IntegrationTestSupport.getUsername(gatewayId, tenantId);
    final String edgeDeviceId = helper.getRandomDeviceId(tenantId);
    final Promise<Void> provisioningNotificationReceived = Promise.promise();
    helper.createAutoProvisioningMessageConsumers(ctx, provisioningNotificationReceived, tenantId, edgeDeviceId).compose(ok -> helper.registry.addDeviceForTenant(tenantId, new Tenant(), gatewayId, gateway, DEVICE_PASSWORD)).compose(ok -> connectToAdapter(username, DEVICE_PASSWORD)).compose(con -> createProducer(null, ProtonQoS.AT_LEAST_ONCE)).compose(sender -> {
        final Message msg = ProtonHelper.message("apFoobar");
        msg.setContentType("text/plain");
        msg.setAddress(String.format("%s/%s/%s", getEndpointName(), tenantId, edgeDeviceId));
        final Promise<Void> result = Promise.promise();
        sender.send(msg, delivery -> {
            ctx.verify(() -> assertThat(delivery.getRemoteState()).isInstanceOf(Accepted.class));
            result.complete();
        });
        return result.future();
    }).compose(ok -> provisioningNotificationReceived.future()).compose(ok -> helper.registry.getRegistrationInfo(tenantId, edgeDeviceId)).onComplete(ctx.succeeding(registrationResult -> {
        ctx.verify(() -> {
            final var info = registrationResult.bodyAsJsonObject();
            IntegrationTestSupport.assertDeviceStatusProperties(info.getJsonObject(RegistryManagementConstants.FIELD_STATUS), true);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Symbol(org.apache.qpid.proton.amqp.Symbol) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) Binary(org.apache.qpid.proton.amqp.Binary) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Data(org.apache.qpid.proton.amqp.messaging.Data) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) LinkError(org.apache.qpid.proton.amqp.transport.LinkError) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Buffer(io.vertx.core.buffer.Buffer) Assertions(org.junit.jupiter.api.Assertions) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) Promise(io.vertx.core.Promise) Tenant(org.eclipse.hono.service.management.tenant.Tenant) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) Message(org.apache.qpid.proton.message.Message) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Device(org.eclipse.hono.service.management.device.Device) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Example 43 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class HonoConnectionImplTest method testCreateReceiverFailsOnDisconnectBeforeOpen.

/**
 * Verifies that the attempt to create a receiver fails with a
 * {@code ServerErrorException} if the connection gets disconnected
 * before the remote peer has sent its attach frame. It is verified
 * that this is done before the link establishment timeout.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateReceiverFailsOnDisconnectBeforeOpen(final VertxTestContext ctx) {
    // choose a distinct value here
    final long linkEstablishmentTimeout = 444L;
    props.setLinkEstablishmentTimeout(linkEstablishmentTimeout);
    // don't run linkEstablishmentTimeout timer handler
    when(vertx.setTimer(eq(linkEstablishmentTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> 0L);
    final Source source = mock(Source.class);
    when(source.getAddress()).thenReturn("source/address");
    final ProtonReceiver receiver = mock(ProtonReceiver.class);
    when(receiver.isOpen()).thenReturn(Boolean.TRUE);
    when(receiver.getSource()).thenReturn(source);
    when(receiver.getRemoteSource()).thenReturn(source);
    when(session.createReceiver(anyString())).thenReturn(receiver);
    final Handler<String> remoteCloseHook = VertxMockSupport.mockHandler();
    // GIVEN an established connection
    honoConnection.connect().compose(c -> {
        // WHEN creating a receiver link with a close hook
        final Future<ProtonReceiver> result = honoConnection.createReceiver("source", ProtonQoS.AT_LEAST_ONCE, mock(ProtonMessageHandler.class), remoteCloseHook);
        // THEN the result is not completed at first
        ctx.verify(() -> assertThat(result.isComplete()).isFalse());
        // WHEN the downstream connection fails
        connectionFactory.getDisconnectHandler().handle(con);
        return result;
    }).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(((ServerErrorException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE));
        ctx.completeNow();
    }));
}
Also used : ProtonReceiver(io.vertx.proton.ProtonReceiver) HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) SaslSystemException(io.vertx.proton.sasl.SaslSystemException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Mockito.doAnswer(org.mockito.Mockito.doAnswer) DisconnectListener(org.eclipse.hono.client.DisconnectListener) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Predicate(java.util.function.Predicate) ProtonQoS(io.vertx.proton.ProtonQoS) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) AdditionalAnswers(org.mockito.AdditionalAnswers) Test(org.junit.jupiter.api.Test) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) ProtonSender(io.vertx.proton.ProtonSender) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Target(org.apache.qpid.proton.amqp.messaging.Target) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Symbol(org.apache.qpid.proton.amqp.Symbol) BiConsumer(java.util.function.BiConsumer) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) AsyncResult(io.vertx.core.AsyncResult) HonoConnection(org.eclipse.hono.client.HonoConnection) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Mockito.never(org.mockito.Mockito.never) Source(org.apache.qpid.proton.amqp.transport.Source) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Source(org.apache.qpid.proton.amqp.transport.Source) Test(org.junit.jupiter.api.Test)

Example 44 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class HonoConnectionImplTest method testIsConnectedWithTimeoutSucceedsAfterConcurrentReconnectSucceeded.

/**
 * Verifies that {@link HonoConnectionImpl#isConnected(long)} only completes once a concurrent
 * connection attempt (which eventually succeeds here) is finished.
 *
 * @param ctx The test execution context.
 */
@Test
public void testIsConnectedWithTimeoutSucceedsAfterConcurrentReconnectSucceeded(final VertxTestContext ctx) {
    final long isConnectedTimeout = 44444L;
    // let the vertx timer for the isConnectedTimeout do nothing
    when(vertx.setTimer(eq(isConnectedTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> 0L);
    final AtomicBoolean isConnectedInvocationsDone = new AtomicBoolean(false);
    final AtomicReference<Future<Void>> isConnected1FutureRef = new AtomicReference<>();
    final AtomicReference<Future<Void>> isConnectedTimeoutForcedFutureRef = new AtomicReference<>();
    final AtomicReference<Future<Void>> isConnected2FutureRef = new AtomicReference<>();
    // GIVEN a client that is configured to connect to a peer
    // to which the connection can be established on the third attempt only
    connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con) {

        @Override
        public void connect(final ProtonClientOptions options, final String username, final String password, final String containerId, final Handler<AsyncResult<ProtonConnection>> closeHandler, final Handler<ProtonConnection> disconnectHandler, final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
            // and GIVEN "isConnected" invocations done while the "connect" invocation is still in progress
            if (isConnectedInvocationsDone.compareAndSet(false, true)) {
                isConnected1FutureRef.set(honoConnection.isConnected(isConnectedTimeout));
                isConnectedTimeoutForcedFutureRef.set(honoConnection.isConnected(1L));
                isConnected2FutureRef.set(honoConnection.isConnected(isConnectedTimeout));
                // assert "isConnected" invocations have not completed yet, apart from the one with the forced timeout
                ctx.verify(() -> {
                    assertThat(isConnected1FutureRef.get().isComplete()).isFalse();
                    assertThat(isConnectedTimeoutForcedFutureRef.get().failed()).isTrue();
                    assertThat(isConnected2FutureRef.get().isComplete()).isFalse();
                });
            }
            super.connect(options, username, password, containerId, closeHandler, disconnectHandler, connectionResultHandler);
        }
    };
    connectionFactory.setExpectedFailingConnectionAttempts(2);
    props.setReconnectAttempts(2);
    props.setConnectTimeout(10);
    honoConnection = new HonoConnectionImpl(vertx, connectionFactory, props);
    // WHEN trying to connect
    honoConnection.connect().compose(v -> CompositeFuture.all(isConnected1FutureRef.get(), isConnected2FutureRef.get())).onFailure(ctx::failNow);
    ctx.verify(() -> {
        // and the client fails twice to connect
        assertThat(connectionFactory.awaitFailure()).isTrue();
        // and succeeds to connect on the third attempt
        assertThat(connectionFactory.await()).isTrue();
    });
    ctx.completeNow();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) SaslSystemException(io.vertx.proton.sasl.SaslSystemException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Mockito.doAnswer(org.mockito.Mockito.doAnswer) DisconnectListener(org.eclipse.hono.client.DisconnectListener) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Predicate(java.util.function.Predicate) ProtonQoS(io.vertx.proton.ProtonQoS) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) AdditionalAnswers(org.mockito.AdditionalAnswers) Test(org.junit.jupiter.api.Test) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) ProtonSender(io.vertx.proton.ProtonSender) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Target(org.apache.qpid.proton.amqp.messaging.Target) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Symbol(org.apache.qpid.proton.amqp.Symbol) BiConsumer(java.util.function.BiConsumer) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) AsyncResult(io.vertx.core.AsyncResult) HonoConnection(org.eclipse.hono.client.HonoConnection) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Mockito.never(org.mockito.Mockito.never) Source(org.apache.qpid.proton.amqp.transport.Source) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ProtonConnection(io.vertx.proton.ProtonConnection) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.jupiter.api.Test)

Example 45 with TIMEOUT

use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.

the class ConnectionFactoryImplTest method testConnectInvokesHandlerOnConnectTimeout.

/**
 * Verifies that the given result handler is invoked if a connection attempt times out.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectInvokesHandlerOnConnectTimeout(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);
    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();
    }));
    timeoutHandlerRef.get().handle(1L);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) Timeout(io.vertx.junit5.Timeout) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Handler(io.vertx.core.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Aggregations

Timeout (io.vertx.junit5.Timeout)75 VertxTestContext (io.vertx.junit5.VertxTestContext)70 Test (org.junit.jupiter.api.Test)69 TimeUnit (java.util.concurrent.TimeUnit)64 Truth.assertThat (com.google.common.truth.Truth.assertThat)62 Future (io.vertx.core.Future)53 HttpURLConnection (java.net.HttpURLConnection)50 Handler (io.vertx.core.Handler)47 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)47 BeforeEach (org.junit.jupiter.api.BeforeEach)45 Buffer (io.vertx.core.buffer.Buffer)44 Promise (io.vertx.core.Promise)43 Vertx (io.vertx.core.Vertx)38 JsonObject (io.vertx.core.json.JsonObject)37 VertxExtension (io.vertx.junit5.VertxExtension)37 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)37 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)36 MethodSource (org.junit.jupiter.params.provider.MethodSource)34 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)33 Tenant (org.eclipse.hono.service.management.tenant.Tenant)33