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();
}
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));
}
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());
}
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);
}
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);
}
}
Aggregations