Search in sources :

Example 11 with TestContext

use of io.vertx.ext.unit.TestContext in project vertx-proton by vert-x3.

the class ProtonClientSslTest method testConnectWithSslSucceeds.

@Test(timeout = 20000)
public void testConnectWithSslSucceeds(TestContext context) throws Exception {
    Async async = context.async();
    // Create a server that accept a connection and expects a client connection+session+receiver
    ProtonServerOptions serverOptions = new ProtonServerOptions();
    serverOptions.setSsl(true);
    PfxOptions serverPfxOptions = new PfxOptions().setPath(KEYSTORE).setPassword(PASSWORD);
    serverOptions.setPfxKeyCertOptions(serverPfxOptions);
    protonServer = createServer(serverOptions, this::handleClientConnectionSessionReceiverOpen);
    // Connect the client and open a receiver to verify the connection works
    ProtonClientOptions clientOptions = new ProtonClientOptions();
    clientOptions.setSsl(true);
    PfxOptions clientPfxOptions = new PfxOptions().setPath(TRUSTSTORE).setPassword(PASSWORD);
    clientOptions.setPfxTrustOptions(clientPfxOptions);
    ProtonClient client = ProtonClient.create(vertx);
    client.connect(clientOptions, "localhost", protonServer.actualPort(), res -> {
        // Expect connect to succeed
        context.assertTrue(res.succeeded());
        ProtonConnection connection = res.result();
        connection.open();
        ProtonReceiver receiver = connection.createReceiver("some-address");
        receiver.openHandler(recvResult -> {
            context.assertTrue(recvResult.succeeded());
            LOG.trace("Client reciever open");
            async.complete();
        }).open();
    });
    async.awaitSuccess();
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) LoggerFactory(io.vertx.core.logging.LoggerFactory) PfxOptions(io.vertx.core.net.PfxOptions) ExecutionException(java.util.concurrent.ExecutionException) After(org.junit.After) ClientAuth(io.vertx.core.http.ClientAuth) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) Before(org.junit.Before) Async(io.vertx.ext.unit.Async) PfxOptions(io.vertx.core.net.PfxOptions) Test(org.junit.Test)

Example 12 with TestContext

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

the class StandaloneEventApiTest method prepareHonoServer.

/**
 * Sets up Hono Messaging service.
 *
 * @param ctx The 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 EventEndpoint eventEndpoint = new EventEndpoint(vertx);
    eventEndpoint.setMetrics(mock(MessagingMetrics.class));
    eventEndpoint.setEventAdapter(downstreamAdapter);
    eventEndpoint.setRegistrationAssertionValidator(assertionHelper);
    eventEndpoint.setConfiguration(configProperties);
    server = new HonoMessaging();
    server.setSaslAuthenticatorFactory(new HonoSaslAuthenticatorFactory(TestSupport.createAuthenticationService(createUser())));
    server.setConfig(configProperties);
    server.addEndpoint(eventEndpoint);
    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 : EventEndpoint(org.eclipse.hono.event.impl.EventEndpoint) 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) ClientErrorException(org.eclipse.hono.client.ClientErrorException) HonoUser(org.eclipse.hono.auth.HonoUser) Constants(org.eclipse.hono.util.Constants) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Message(org.apache.qpid.proton.message.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Activity(org.eclipse.hono.auth.Activity) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TestSupport(org.eclipse.hono.TestSupport) Authorities(org.eclipse.hono.auth.Authorities) HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) Mockito.mock(org.mockito.Mockito.mock) EventEndpoint(org.eclipse.hono.event.impl.EventEndpoint) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) BeforeClass(org.junit.BeforeClass)

Example 13 with TestContext

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

the class StandaloneEventApiTest method testMalformedMessageGetsRejected.

/**
 * Verifies that malformed messages are not forwarded downstream.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testMalformedMessageGetsRejected(final TestContext ctx) {
    final Message msg = ProtonHelper.message("malformed");
    msg.setMessageId("malformed-message");
    final Future<MessageSender> senderTracker = getSender(Constants.DEFAULT_TENANT);
    senderTracker.compose(sender -> {
        return sender.send(msg);
    }).setHandler(ctx.asyncAssertFailure(t -> {
        ctx.assertTrue(ClientErrorException.class.isInstance(t));
        ctx.assertTrue(senderTracker.result().isOpen());
    }));
}
Also used : 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) ClientErrorException(org.eclipse.hono.client.ClientErrorException) HonoUser(org.eclipse.hono.auth.HonoUser) Constants(org.eclipse.hono.util.Constants) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Message(org.apache.qpid.proton.message.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Activity(org.eclipse.hono.auth.Activity) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TestSupport(org.eclipse.hono.TestSupport) Authorities(org.eclipse.hono.auth.Authorities) HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) Mockito.mock(org.mockito.Mockito.mock) EventEndpoint(org.eclipse.hono.event.impl.EventEndpoint) Message(org.apache.qpid.proton.message.Message) MessageSender(org.eclipse.hono.client.MessageSender) Test(org.junit.Test)

Example 14 with TestContext

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

the class ClientTestBase method testSendingMessages.

/**
 * Verifies that a number of messages uploaded to Hono's Telemetry or Event API can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if test execution is interrupted.
 */
@Test
public void testSendingMessages(final TestContext ctx) throws InterruptedException {
    final CountDownLatch received = new CountDownLatch(IntegrationTestSupport.MSG_COUNT);
    final Async setup = ctx.async();
    final AtomicReference<String> registrationAssertion = new AtomicReference<>();
    registrationClient.register(DEVICE_ID, null).compose(ok -> registrationClient.assertRegistration(DEVICE_ID)).compose(result -> {
        registrationAssertion.set(result.getString(RegistrationConstants.FIELD_ASSERTION));
        return createConsumer(TEST_TENANT_ID, msg -> {
            LOGGER.trace("received {}", msg);
            assertMessageProperties(ctx, msg);
            assertAdditionalMessageProperties(ctx, msg);
            received.countDown();
            if (received.getCount() % 200 == 0) {
                LOGGER.info("messages received: {}", IntegrationTestSupport.MSG_COUNT - received.getCount());
            }
        });
    }).map(c -> {
        consumer = c;
        setup.complete();
        return null;
    });
    setup.await(1000);
    long start = System.currentTimeMillis();
    final AtomicInteger messagesSent = new AtomicInteger();
    while (messagesSent.get() < IntegrationTestSupport.MSG_COUNT) {
        final Async sending = ctx.async();
        sender.send(DEVICE_ID, "payload_" + messagesSent.getAndIncrement(), CONTENT_TYPE_TEXT_PLAIN, registrationAssertion.get(), creditAvailable -> sending.complete());
        if (messagesSent.get() % 200 == 0) {
            LOGGER.info("messages sent: " + messagesSent.get());
        }
        sending.await();
    }
    long timeToWait = Math.max(DEFAULT_TEST_TIMEOUT, Math.round(IntegrationTestSupport.MSG_COUNT * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messagesSent.get(), IntegrationTestSupport.MSG_COUNT - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messagesSent.get(), IntegrationTestSupport.MSG_COUNT - received.getCount(), System.currentTimeMillis() - start);
    }
}
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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 15 with TestContext

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

the class ClientTestBase method connect.

/**
 * Sets up the environment:
 * <ol>
 * <li>connect to the AMQP messaging network</li>
 * <li>connects to the Hono Server</li>
 * <li>connects to the Hono Device Registry</li>
 * <li>creates a RegistrationClient for TEST_TENANT_ID</li>
 * <li>creates a MessageSender for TEST_TENANT_ID</li>
 * </ul>
 *
 * @param ctx The test context
 */
@Before
public void connect(final TestContext ctx) {
    final ClientConfigProperties downstreamProps = new ClientConfigProperties();
    downstreamProps.setHost(IntegrationTestSupport.DOWNSTREAM_HOST);
    downstreamProps.setPort(IntegrationTestSupport.DOWNSTREAM_PORT);
    downstreamProps.setPathSeparator(IntegrationTestSupport.PATH_SEPARATOR);
    downstreamProps.setUsername(IntegrationTestSupport.RESTRICTED_CONSUMER_NAME);
    downstreamProps.setPassword(IntegrationTestSupport.RESTRICTED_CONSUMER_PWD);
    downstreamClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(downstreamProps).vertx(vertx).build(), downstreamProps);
    final ClientConfigProperties honoProps = new ClientConfigProperties();
    honoProps.setHost(IntegrationTestSupport.HONO_HOST);
    honoProps.setPort(IntegrationTestSupport.HONO_PORT);
    honoProps.setUsername(IntegrationTestSupport.HONO_USER);
    honoProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(honoProps).vertx(vertx).build(), honoProps);
    final ClientConfigProperties registryProps = new ClientConfigProperties();
    registryProps.setHost(IntegrationTestSupport.HONO_DEVICEREGISTRY_HOST);
    registryProps.setPort(IntegrationTestSupport.HONO_DEVICEREGISTRY_AMQP_PORT);
    registryProps.setUsername(IntegrationTestSupport.HONO_USER);
    registryProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoDeviceRegistryClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(registryProps).vertx(vertx).build(), registryProps);
    final ProtonClientOptions options = new ProtonClientOptions();
    // connect to AMQP messaging network
    final Future<HonoClient> downstreamTracker = downstreamClient.connect(options);
    // create sender
    final Future<MessageSender> senderTracker = honoClient.connect(options).compose(connectedClient -> createProducer(TEST_TENANT_ID)).map(s -> {
        sender = s;
        return s;
    });
    // create registration client
    final Future<RegistrationClient> registrationClientTracker = honoDeviceRegistryClient.connect(options).compose(connectedClient -> connectedClient.getOrCreateRegistrationClient(TEST_TENANT_ID)).map(c -> {
        registrationClient = c;
        return c;
    });
    CompositeFuture.all(downstreamTracker, senderTracker, registrationClientTracker).setHandler(ctx.asyncAssertSuccess(s -> {
        LOGGER.info("connections to Hono server, Hono device registry and AMQP messaging network established");
    }));
}
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) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) HonoClient(org.eclipse.hono.client.HonoClient) MessageSender(org.eclipse.hono.client.MessageSender) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Before(org.junit.Before)

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