Search in sources :

Example 91 with TestContext

use of io.vertx.ext.unit.TestContext in project hono by eclipse.

the class AbstractRequestResponseClientTest method testCreateAndSendRequestFailsOnRejectedMessage.

/**
 * Verifies that the client fails the result handler if the peer rejects
 * the request message.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCreateAndSendRequestFailsOnRejectedMessage(final TestContext ctx) {
    // GIVEN a request-response client that times out requests after 200 ms
    client.setRequestTimeout(200);
    // WHEN sending a request message with some headers and payload
    final Async sendFailure = ctx.async();
    final JsonObject payload = new JsonObject().put("key", "value");
    client.createAndSendRequest("get", null, payload, ctx.asyncAssertFailure(t -> {
        sendFailure.complete();
    }));
    // and the peer rejects the message
    final Rejected rejected = new Rejected();
    rejected.setError(ProtonHelper.condition("bad-request", "request message is malformed"));
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    when(delivery.getRemoteState()).thenReturn(rejected);
    final ArgumentCaptor<Handler> dispositionHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).send(any(Message.class), dispositionHandlerCaptor.capture());
    dispositionHandlerCaptor.getValue().handle(delivery);
    // THEN the result handler is failed
    sendFailure.await();
}
Also used : 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) CoreMatchers(org.hamcrest.CoreMatchers) Async(io.vertx.ext.unit.Async) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) 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) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) Target(org.apache.qpid.proton.amqp.transport.Target) Duration(java.time.Duration) Map(java.util.Map) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) Async(io.vertx.ext.unit.Async) JsonObject(io.vertx.core.json.JsonObject) Handler(io.vertx.core.Handler) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Test(org.junit.Test)

Example 92 with TestContext

use of io.vertx.ext.unit.TestContext in project hono by eclipse.

the class AbstractRequestResponseClientTest method testCreateAndSendRequestDoesNotAddNonCacheableResponseToCache.

/**
 * Verifies that the adapter does not put a response from the service to the cache
 * that does not contain any cache directive but has a <em>non-cacheable</em> status code.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testCreateAndSendRequestDoesNotAddNonCacheableResponseToCache(final TestContext ctx) {
    // GIVEN an adapter with an empty cache
    client.setResponseCache(cache);
    // WHEN getting a 404 response to a request which contains
    // no cache directive
    final Async invocation = ctx.async();
    client.createAndSendRequest("get", (JsonObject) null, ctx.asyncAssertSuccess(result -> invocation.complete()), "cacheKey");
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), any(Handler.class));
    final Message response = ProtonHelper.message();
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_NOT_FOUND);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
    // THEN the response is not put to the cache
    invocation.await();
    verify(cache, never()).put(eq("cacheKey"), any(SimpleRequestResponseResult.class), any(Duration.class));
}
Also used : 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) CoreMatchers(org.hamcrest.CoreMatchers) Async(io.vertx.ext.unit.Async) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) 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) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) Target(org.apache.qpid.proton.amqp.transport.Target) Duration(java.time.Duration) Map(java.util.Map) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Message(org.apache.qpid.proton.message.Message) ProtonDelivery(io.vertx.proton.ProtonDelivery) Async(io.vertx.ext.unit.Async) Handler(io.vertx.core.Handler) Duration(java.time.Duration) Test(org.junit.Test)

Example 93 with TestContext

use of io.vertx.ext.unit.TestContext in project hono by eclipse.

the class StandaloneTelemetryApiTest method prepareHonoServer.

/**
 * Sets up the fixture common to all test cases.
 *
 * @param ctx The vert.x test context.
 */
@BeforeClass
public static void prepareHonoServer(final TestContext ctx) {
    vertx = Vertx.vertx();
    downstreamAdapter = new MessageDiscardingDownstreamAdapter(vertx);
    final HonoMessagingConfigProperties configProperties = new HonoMessagingConfigProperties();
    configProperties.setInsecurePort(0);
    final TelemetryEndpoint telemetryEndpoint = new TelemetryEndpoint(vertx);
    telemetryEndpoint.setMetrics(mock(MessagingMetrics.class));
    telemetryEndpoint.setTelemetryAdapter(downstreamAdapter);
    telemetryEndpoint.setRegistrationAssertionValidator(assertionHelper);
    telemetryEndpoint.setConfiguration(configProperties);
    server = new HonoMessaging();
    server.setSaslAuthenticatorFactory(new HonoSaslAuthenticatorFactory(TestSupport.createAuthenticationService(createUser())));
    server.setConfig(configProperties);
    server.addEndpoint(telemetryEndpoint);
    final Future<String> serverTracker = Future.future();
    vertx.deployVerticle(server, serverTracker.completer());
    serverTracker.compose(s -> {
        final ClientConfigProperties clientProps = new ClientConfigProperties();
        clientProps.setName("test");
        clientProps.setHost(server.getInsecurePortBindAddress());
        clientProps.setPort(server.getInsecurePort());
        clientProps.setUsername(USER);
        clientProps.setPassword(PWD);
        client = new HonoClientImpl(vertx, clientProps);
        return client.connect(new ProtonClientOptions());
    }).setHandler(ctx.asyncAssertSuccess());
}
Also used : HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) TestContext(io.vertx.ext.unit.TestContext) AuthoritiesImpl(org.eclipse.hono.auth.AuthoritiesImpl) HonoUserAdapter(org.eclipse.hono.auth.HonoUserAdapter) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Activity(org.eclipse.hono.auth.Activity) HonoUser(org.eclipse.hono.auth.HonoUser) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) Future(io.vertx.core.Future) TelemetryEndpoint(org.eclipse.hono.telemetry.impl.TelemetryEndpoint) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) TestSupport(org.eclipse.hono.TestSupport) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Authorities(org.eclipse.hono.auth.Authorities) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) Mockito.mock(org.mockito.Mockito.mock) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) TelemetryEndpoint(org.eclipse.hono.telemetry.impl.TelemetryEndpoint) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) BeforeClass(org.junit.BeforeClass)

Example 94 with TestContext

use of io.vertx.ext.unit.TestContext in project hono by eclipse.

the class ClientTestBase method disconnect.

private void disconnect(final TestContext ctx) {
    final Async shutdown = ctx.async();
    final Future<Void> honoTracker = Future.future();
    final Future<Void> qpidTracker = Future.future();
    CompositeFuture.all(honoTracker, qpidTracker).setHandler(r -> {
        if (r.failed()) {
            LOGGER.info("error while disconnecting: ", r.cause());
        }
        shutdown.complete();
    });
    if (sender != null) {
        final Future<Void> regClientTracker = Future.future();
        registrationClient.close(regClientTracker.completer());
        regClientTracker.compose(r -> {
            Future<Void> senderTracker = Future.future();
            sender.close(senderTracker.completer());
            return senderTracker;
        }).compose(r -> {
            Future<Void> honoClientShutdownTracker = Future.future();
            honoClient.shutdown(honoClientShutdownTracker.completer());
            return honoClientShutdownTracker;
        }).compose(r -> {
            honoDeviceRegistryClient.shutdown(honoTracker.completer());
        }, honoTracker);
    } else {
        honoTracker.complete();
    }
    Future<Void> receiverTracker = Future.future();
    if (consumer != null) {
        consumer.close(receiverTracker.completer());
    } else {
        receiverTracker.complete();
    }
    receiverTracker.compose(r -> {
        downstreamClient.shutdown(qpidTracker.completer());
    }, qpidTracker);
    shutdown.await(2000);
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionFactoryBuilder(org.eclipse.hono.connection.ConnectionFactoryImpl.ConnectionFactoryBuilder) MessageSender(org.eclipse.hono.client.MessageSender) After(org.junit.After) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Async(io.vertx.ext.unit.Async) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future)

Example 95 with TestContext

use of io.vertx.ext.unit.TestContext in project hono by eclipse.

the class HttpTestBase method testUploadMessages.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessages(final TestContext ctx) throws InterruptedException {
    final int messagesToSend = 100;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addTenant(JsonObject.mapFrom(tenant)).compose(ok -> helper.registry.registerDevice(tenantId, deviceId)).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 20 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    while (messageCount.get() < messagesToSend) {
        final Async sending = ctx.async();
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement())).setHandler(attempt -> {
            if (attempt.succeeded()) {
                LOGGER.debug("sent message {} [status code: 202]", messageCount.get());
            } else {
                LOGGER.debug("sent message {} [status code: {}]", messageCount.get(), ((ServiceInvocationException) attempt.cause()).getErrorCode());
            }
            sending.complete();
        });
        if (messageCount.get() % 20 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sending.await();
    }
    long timeToWait = Math.max(TEST_TIMEOUT - 1000, Math.round(messagesToSend * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

TestContext (io.vertx.ext.unit.TestContext)148 Test (org.junit.Test)147 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)141 RunWith (org.junit.runner.RunWith)141 Async (io.vertx.ext.unit.Async)123 Future (io.vertx.core.Future)121 Handler (io.vertx.core.Handler)112 Vertx (io.vertx.core.Vertx)103 HttpURLConnection (java.net.HttpURLConnection)100 Before (org.junit.Before)97 Timeout (org.junit.rules.Timeout)95 JsonObject (io.vertx.core.json.JsonObject)91 Rule (org.junit.Rule)83 Mockito (org.mockito.Mockito)74 Constants (org.eclipse.hono.util.Constants)68 Assert.assertThat (org.junit.Assert.assertThat)62 Context (io.vertx.core.Context)57 CoreMatchers.is (org.hamcrest.CoreMatchers.is)54 AsyncResult (io.vertx.core.AsyncResult)53 Buffer (io.vertx.core.buffer.Buffer)52