Search in sources :

Example 1 with Timeout

use of io.vertx.junit5.Timeout 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();
}
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) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) AsyncResult(io.vertx.core.AsyncResult) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 2 with Timeout

use of io.vertx.junit5.Timeout 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();
}
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) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) AsyncResult(io.vertx.core.AsyncResult) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 3 with Timeout

use of io.vertx.junit5.Timeout in project hono by eclipse.

the class HonoProtonHelperTest method testExecuteOnContextRunsOnGivenContext.

/**
 * Verifies that code is scheduled to be executed on a given Context
 * other than the current Context.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testExecuteOnContextRunsOnGivenContext(final VertxTestContext ctx) {
    final Context mockContext = mock(Context.class);
    doAnswer(invocation -> {
        final Handler<Void> codeToRun = invocation.getArgument(0);
        codeToRun.handle(null);
        return null;
    }).when(mockContext).runOnContext(any(Handler.class));
    HonoProtonHelper.executeOnContext(mockContext, result -> result.complete("done")).onComplete(ctx.succeeding(s -> {
        ctx.verify(() -> {
            verify(mockContext).runOnContext(any(Handler.class));
            assertThat(s).isEqualTo("done");
        });
        ctx.completeNow();
    }));
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) Context(io.vertx.core.Context) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Handler(io.vertx.core.Handler) Mockito.mock(org.mockito.Mockito.mock) Handler(io.vertx.core.Handler) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 4 with Timeout

use of io.vertx.junit5.Timeout in project hono by eclipse.

the class HonoConnectionImplTest method testCreateSenderFailsOnDisconnectBeforeOpen.

/**
 * Verifies that the attempt to create a sender 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 testCreateSenderFailsOnDisconnectBeforeOpen(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 ProtonSender sender = mock(ProtonSender.class);
    when(sender.isOpen()).thenReturn(Boolean.TRUE);
    when(session.createSender(anyString())).thenReturn(sender);
    final Target target = new Target();
    target.setAddress("someAddress");
    when(sender.getRemoteTarget()).thenReturn(target);
    when(sender.getCredit()).thenReturn(0);
    // mock handlers
    final Handler<String> remoteCloseHook = VertxMockSupport.mockHandler();
    // GIVEN an established connection
    honoConnection.connect().compose(c -> {
        // WHEN creating a sender link with a close hook
        final Future<ProtonSender> result = honoConnection.createSender("target", ProtonQoS.AT_LEAST_ONCE, 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 : 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) ProtonSender(io.vertx.proton.ProtonSender) Target(org.apache.qpid.proton.amqp.messaging.Target) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.jupiter.api.Test)

Example 5 with Timeout

use of io.vertx.junit5.Timeout in project hono by eclipse.

the class RequestResponseClientTest method testCreateAndSendRequestSetsNoTimerIfRequestTimeoutZero.

/**
 * Verifies that the client configured with a zero request timeout sets no timer for
 * canceling the request in case of no received response.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestSetsNoTimerIfRequestTimeoutZero(final VertxTestContext ctx) {
    // WHEN configuring the client with a zero request timeout and sending a request message
    final JsonObject payload = new JsonObject().put("key", "value");
    client.map(c -> {
        c.setRequestTimeout(0);
        return c;
    }).onComplete(ctx.succeeding(c -> {
        c.createAndSendRequest("get", null, payload.toBuffer(), "application/json", SimpleRequestResponseResult::from, span);
    }));
    // THEN the message is sent
    final Message request = verifySenderSend();
    assertThat(request).isNotNull();
    assertThat(request.getBody()).isNotNull();
    assertThat(request.getBody()).isInstanceOf(Data.class);
    final Buffer body = MessageHelper.getPayload(request);
    assertThat(body.getBytes()).isEqualTo(payload.toBuffer().getBytes());
    // and no timer has been set to time out the request
    verify(vertx, never()).setTimer(anyLong(), VertxMockSupport.anyHandler());
    ctx.completeNow();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Timeout(io.vertx.junit5.Timeout) EventBus(io.vertx.core.eventbus.EventBus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) JsonObject(io.vertx.core.json.JsonObject) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) Data(org.apache.qpid.proton.amqp.messaging.Data) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) ProtonSender(io.vertx.proton.ProtonSender) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) AmqpClientUnitTestHelper(org.eclipse.hono.client.amqp.test.AmqpClientUnitTestHelper) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ArgumentCaptor(org.mockito.ArgumentCaptor) Symbol(org.apache.qpid.proton.amqp.Symbol) Message(org.apache.qpid.proton.message.Message) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) HonoConnection(org.eclipse.hono.client.HonoConnection) ArgumentMatchers.isA(org.mockito.ArgumentMatchers.isA) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Tracer(io.opentracing.Tracer) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) 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) Consumer(java.util.function.Consumer) Mockito.never(org.mockito.Mockito.never) ResourceLimitExceededException(org.eclipse.hono.client.ResourceLimitExceededException) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Buffer(io.vertx.core.buffer.Buffer) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Aggregations

Timeout (io.vertx.junit5.Timeout)73 VertxTestContext (io.vertx.junit5.VertxTestContext)73 Test (org.junit.jupiter.api.Test)71 TimeUnit (java.util.concurrent.TimeUnit)67 Truth.assertThat (com.google.common.truth.Truth.assertThat)65 Future (io.vertx.core.Future)54 HttpURLConnection (java.net.HttpURLConnection)52 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)49 Handler (io.vertx.core.Handler)47 Buffer (io.vertx.core.buffer.Buffer)46 BeforeEach (org.junit.jupiter.api.BeforeEach)46 Promise (io.vertx.core.Promise)45 Vertx (io.vertx.core.Vertx)37 JsonObject (io.vertx.core.json.JsonObject)37 VertxExtension (io.vertx.junit5.VertxExtension)37 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)37 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)37 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)37 Tenant (org.eclipse.hono.service.management.tenant.Tenant)36 MethodSource (org.junit.jupiter.params.provider.MethodSource)35