Search in sources :

Example 96 with TestContext

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

the class MqttTestBase method doTestUploadMessages.

/**
 * 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.
 * @param useShortTopicName Whether to use standard or short topic names
 * @throws InterruptedException if the test fails.
 */
public void doTestUploadMessages(final TestContext ctx, boolean useShortTopicName) throws InterruptedException {
    final int messagesToSend = 200;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addDeviceForTenant(tenant, deviceId, password).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 40 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).compose(ok -> {
        final Future<MqttConnAckMessage> result = Future.future();
        final MqttClientOptions options = new MqttClientOptions().setMaxInflightQueue(200).setUsername(IntegrationTestSupport.getUsername(deviceId, tenantId)).setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result.completer());
        return result;
    }).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    final AtomicReference<Async> sendResult = new AtomicReference<>();
    mqttClient.publishCompletionHandler(packetId -> {
        if (pendingMessages.remove(packetId)) {
            sendResult.get().complete();
        } else {
            LOGGER.info("received PUBACK for unexpected message [id: {}]", packetId);
        }
    });
    while (messageCount.get() < messagesToSend) {
        sendResult.set(ctx.async());
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement()), useShortTopicName, sendAttempt -> {
            if (sendAttempt.failed()) {
                LOGGER.debug("error sending message {}", messageCount.get(), sendAttempt.cause());
            } else {
                pendingMessages.add(sendAttempt.result());
            }
        });
        if (messageCount.get() % 40 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sendResult.get().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 : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) MqttClient(io.vertx.mqtt.MqttClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) AsyncResult(io.vertx.core.AsyncResult) MqttConnAckMessage(io.vertx.mqtt.messages.MqttConnAckMessage) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Set(java.util.Set) 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) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) MqttClientOptions(io.vertx.mqtt.MqttClientOptions) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 97 with TestContext

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

the class CredentialsAmqpIT method prepareDeviceRegistry.

/**
 * Starts the device registry and connects a client.
 *
 * @param ctx The vert.x test context.
 */
@BeforeClass
public static void prepareDeviceRegistry(final TestContext ctx) {
    client = DeviceRegistryAmqpTestSupport.prepareDeviceRegistryClient(vertx);
    client.connect(new ProtonClientOptions()).compose(c -> c.getOrCreateCredentialsClient(Constants.DEFAULT_TENANT)).setHandler(ctx.asyncAssertSuccess(r -> {
        credentialsClient = r;
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) BeforeClass(org.junit.BeforeClass) LocalDateTime(java.time.LocalDateTime) RunWith(org.junit.runner.RunWith) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) CredentialsClient(org.eclipse.hono.client.CredentialsClient) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) HonoClient(org.eclipse.hono.client.HonoClient) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) StandardCharsets(java.nio.charset.StandardCharsets) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) TimeUnit(java.util.concurrent.TimeUnit) JsonArray(io.vertx.core.json.JsonArray) Base64(java.util.Base64) Rule(org.junit.Rule) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DateTimeFormatter(java.time.format.DateTimeFormatter) Assert(org.junit.Assert) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) BeforeClass(org.junit.BeforeClass)

Example 98 with TestContext

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

the class CredentialsHttpIT method testUpdateCredentialsSucceeds.

/**
 * Verifies that the service accepts an update credentials request for existing credentials.
 *
 * @param context The vert.x test context.
 */
@Test
public void testUpdateCredentialsSucceeds(final TestContext context) {
    final JsonObject altered = hashedPasswordCredentials.copy();
    altered.put(CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID, "other-device");
    registry.addCredentials(TENANT, hashedPasswordCredentials).compose(ar -> registry.updateCredentials(TENANT, authId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, altered)).compose(ur -> registry.getCredentials(TENANT, authId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD)).setHandler(context.asyncAssertSuccess(gr -> {
        context.assertEquals("other-device", gr.toJsonObject().getString(CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID));
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) After(org.junit.After) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) UUID(java.util.UUID) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Rule(org.junit.Rule) DeviceRegistryHttpClient(org.eclipse.hono.tests.DeviceRegistryHttpClient) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 99 with TestContext

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

the class CredentialsHttpIT method testUpdateCredentialsFailsForNonMatchingTypeInPayload.

/**
 * Verifies that the service rejects an update request for credentials containing a different type.
 *
 * @param context The vert.x test context.
 */
@Test
public void testUpdateCredentialsFailsForNonMatchingTypeInPayload(final TestContext context) {
    final JsonObject altered = hashedPasswordCredentials.copy().put(CredentialsConstants.FIELD_TYPE, "non-matching-type");
    registry.addCredentials(TENANT, hashedPasswordCredentials).compose(ar -> {
        return registry.updateCredentials(TENANT, authId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, altered, HttpURLConnection.HTTP_BAD_REQUEST);
    }).setHandler(context.asyncAssertSuccess());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) CompositeFuture(io.vertx.core.CompositeFuture) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) After(org.junit.After) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) UUID(java.util.UUID) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Rule(org.junit.Rule) DeviceRegistryHttpClient(org.eclipse.hono.tests.DeviceRegistryHttpClient) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 100 with TestContext

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

the class DeviceRegistrationHttpIT method testGetDeviceContainsRegisteredInfo.

/**
 * Verifies that the information that has been registered for a device
 * is contained in the result when retrieving registration information
 * for the device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetDeviceContainsRegisteredInfo(final TestContext ctx) {
    final JsonObject data = new JsonObject().put("testString", "testValue").put("testBoolean", Boolean.FALSE).put(RegistrationConstants.FIELD_ENABLED, Boolean.TRUE);
    registry.registerDevice(TENANT, deviceId, data).compose(ok -> registry.getRegistrationInfo(TENANT, deviceId)).compose(info -> {
        assertRegistrationInformation(ctx, info.toJsonObject(), deviceId, data);
        return Future.succeededFuture();
    }).setHandler(ctx.asyncAssertSuccess());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) AfterClass(org.junit.AfterClass) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) UUID(java.util.UUID) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Future(io.vertx.core.Future) Rule(org.junit.Rule) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) After(org.junit.After) DeviceRegistryHttpClient(org.eclipse.hono.tests.DeviceRegistryHttpClient) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) JsonObject(io.vertx.core.json.JsonObject) 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