use of org.eclipse.hono.tests.AssumeMessagingSystem in project hono by eclipse.
the class CommandAndControlMqttIT method testSendCommandViaAmqpFailsForMalformedMessage.
/**
* Verifies that the adapter rejects malformed command messages sent by applications.
* <p>
* This test is applicable only if the messaging network type is AMQP.
*
* @param endpointConfig The endpoints to use for sending/receiving commands.
* @param ctx The vert.x test context.
* @throws InterruptedException if not all commands and responses are exchanged in time.
*/
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
@AssumeMessagingSystem(type = MessagingType.amqp)
public void testSendCommandViaAmqpFailsForMalformedMessage(final MqttCommandEndpointConfiguration endpointConfig, final VertxTestContext ctx) throws InterruptedException {
final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway() ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5) : deviceId;
final AtomicReference<GenericSenderLink> amqpCmdSenderRef = new AtomicReference<>();
final String linkTargetAddress = endpointConfig.getSenderLinkTargetAddress(tenantId);
final VertxTestContext setup = new VertxTestContext();
final Checkpoint ready = setup.checkpoint(2);
createConsumer(tenantId, msg -> {
// expect empty notification with TTD -1
setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
final TimeUntilDisconnectNotification notification = msg.getTimeUntilDisconnectNotification().orElse(null);
LOGGER.info("received notification [{}]", notification);
if (notification.getTtd() == -1) {
ready.flag();
}
}).compose(consumer -> helper.registry.addDeviceToTenant(tenantId, deviceId, password)).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).compose(conAck -> subscribeToCommands(commandTargetDeviceId, msg -> {
// all commands should get rejected because they fail to pass the validity check
ctx.failNow(new IllegalStateException("should not have received command"));
}, endpointConfig, MqttQoS.AT_MOST_ONCE)).compose(ok -> helper.createGenericAmqpMessageSender(endpointConfig.getNorthboundEndpoint(), tenantId)).onComplete(setup.succeeding(genericSender -> {
LOGGER.debug("created generic sender for sending commands [target address: {}]", linkTargetAddress);
amqpCmdSenderRef.set(genericSender);
ready.flag();
}));
assertWithMessage("setup of adapter finished within %s seconds", IntegrationTestSupport.getTestSetupTimeout()).that(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
final Checkpoint failedAttempts = ctx.checkpoint(2);
final String messageAddress = endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId);
LOGGER.debug("sending command message lacking subject");
final Message messageWithoutSubject = ProtonHelper.message("input data");
messageWithoutSubject.setAddress(messageAddress);
messageWithoutSubject.setMessageId("message-id");
messageWithoutSubject.setReplyTo("reply/to/address");
amqpCmdSenderRef.get().sendAndWaitForOutcome(messageWithoutSubject, NoopSpan.INSTANCE).onComplete(ctx.failing(t -> {
ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
failedAttempts.flag();
}));
LOGGER.debug("sending command message lacking message ID and correlation ID");
final Message messageWithoutId = ProtonHelper.message("input data");
messageWithoutId.setAddress(messageAddress);
messageWithoutId.setSubject("setValue");
messageWithoutId.setReplyTo("reply/to/address");
amqpCmdSenderRef.get().sendAndWaitForOutcome(messageWithoutId, NoopSpan.INSTANCE).onComplete(ctx.failing(t -> {
ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
failedAttempts.flag();
}));
}
use of org.eclipse.hono.tests.AssumeMessagingSystem in project hono by eclipse.
the class TelemetryHttpIT method testUploadMessageFailsForNoConsumer.
/**
* Verifies that the upload of a telemetry message fails with a 503 status code
* when there is no consumer.
*
* @param ctx The test context
*/
@Test
@AssumeMessagingSystem(type = MessagingType.amqp)
public void testUploadMessageFailsForNoConsumer(final VertxTestContext ctx) {
// GIVEN a device
final Tenant tenant = new Tenant();
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> {
// WHEN the device tries to upload a telemetry message while there is no consumer for it
final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, authorization);
return httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, // THEN the message gets rejected by the HTTP adapter with a 503
ResponsePredicate.status(HttpURLConnection.HTTP_UNAVAILABLE));
}).onComplete(ctx.succeeding(response -> {
ctx.verify(() -> {
final var body = response.bodyAsJsonObject();
assertThat(body.getString(RequestResponseApiConstants.FIELD_ERROR)).isEqualTo(ServiceInvocationException.getLocalizedMessage(NoConsumerException.CLIENT_FACING_MESSAGE_KEY));
});
ctx.completeNow();
}));
}
use of org.eclipse.hono.tests.AssumeMessagingSystem in project hono by eclipse.
the class TelemetryHttpIT method testUploadQos1MessageFailsIfDeliveryStateNotUpdated.
/**
* Verifies that the upload of a QoS 1 telemetry message fails with a 503 status code
* when the consumer doesn't update the message delivery state and the
* <em>sendMessageTimeout</em> has elapsed.
*
* @param vertx The vert.x instance.
* @param ctx The test context
* @throws InterruptedException if test is interrupted while running.
*/
@Test
@AssumeMessagingSystem(type = MessagingType.amqp)
public void testUploadQos1MessageFailsIfDeliveryStateNotUpdated(final Vertx vertx, final VertxTestContext ctx) throws InterruptedException {
final AmqpApplicationClient amqpApplicationClient = (AmqpApplicationClient) helper.applicationClient;
// GIVEN a device and a north bound message consumer that doesn't update the message delivery state
final Tenant tenant = new Tenant();
final Checkpoint messageReceived = ctx.checkpoint();
final Checkpoint deliveryStateCheckDone = ctx.checkpoint();
final Checkpoint httpResponseReceived = ctx.checkpoint();
final VertxTestContext setup = new VertxTestContext();
final AtomicReference<ProtonDelivery> deliveryRef = new AtomicReference<>();
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> amqpApplicationClient.createTelemetryConsumer(tenantId, msg -> {
final Promise<Void> result = Promise.promise();
final var delivery = msg.getMessageContext().getDelivery();
deliveryRef.set(delivery);
logger.debug("received message: {}", msg.getMessageContext().getRawMessage());
ctx.verify(() -> {
assertThat(delivery.remotelySettled()).isFalse();
assertThat(delivery.getRemoteState()).isNull();
});
messageReceived.flag();
// don't update the delivery state here
return result.future();
}, remoteClose -> {
})).onComplete(setup.succeedingThenComplete());
assertThat(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
// WHEN the device tries to upload a telemetry message
final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "binary/octet-stream").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_QOS_LEVEL, "1");
final Future<HttpResponse<Buffer>> httpResponseFuture = httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, // THEN the message gets rejected by the HTTP adapter with a 503
ResponsePredicate.status(HttpURLConnection.HTTP_UNAVAILABLE));
httpResponseFuture.onComplete(ctx.succeeding(response -> {
ctx.verify(() -> {
final var body = response.bodyAsJsonObject();
assertThat(body.getString(RequestResponseApiConstants.FIELD_ERROR)).isEqualTo(ServiceInvocationException.getLocalizedMessage(SendMessageTimeoutException.CLIENT_FACING_MESSAGE_KEY));
});
httpResponseReceived.flag();
// verify that the telemetry message delivery is remotely settled via the timeout handling in the adapter
vertx.setTimer(50, tid -> {
ctx.verify(() -> {
final ProtonDelivery delivery = deliveryRef.get();
assertThat(delivery).isNotNull();
assertThat(delivery.remotelySettled()).isTrue();
assertThat(delivery.getRemoteState()).isNotNull();
assertThat(delivery.getRemoteState().getType()).isEqualTo(DeliveryState.DeliveryStateType.Released);
});
deliveryStateCheckDone.flag();
});
}));
}
use of org.eclipse.hono.tests.AssumeMessagingSystem in project hono by eclipse.
the class DeviceRegistryNotificationsIT method testReceiveNotificationViaKafka.
/**
* Verifies that Kafka-based notifications for adding tenant/device/credentials resources are received by a local
* client.
*
* @param ctx The vert.x test context.
* @throws InterruptedException if test is interrupted while running.
*/
@Test
@AssumeMessagingSystem(type = MessagingType.kafka)
public void testReceiveNotificationViaKafka(final VertxTestContext ctx) throws InterruptedException {
final var notificationConsumerConfig = new NotificationKafkaConsumerConfigProperties();
notificationConsumerConfig.setConsumerConfig(IntegrationTestSupport.getKafkaConsumerConfig().getConsumerConfig("notification-receiver"));
receiver = new KafkaBasedNotificationReceiver(vertx, notificationConsumerConfig);
testReceiveNotification(ctx);
}
use of org.eclipse.hono.tests.AssumeMessagingSystem in project hono by eclipse.
the class CommandAndControlAmqpIT method testSendCommandViaKafkaFailsForMalformedMessage.
/**
* Verifies that the adapter rejects malformed command messages sent by applications.
* <p>
* This test is applicable only if the messaging network type is Kafka.
*
* @param endpointConfig The endpoints to use for sending/receiving commands.
* @param ctx The vert.x test context.
* @throws InterruptedException if not all commands and responses are exchanged in time.
*/
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
@AssumeMessagingSystem(type = MessagingType.kafka)
public void testSendCommandViaKafkaFailsForMalformedMessage(final AmqpCommandEndpointConfiguration endpointConfig, final VertxTestContext ctx) throws InterruptedException {
final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway() ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5) : deviceId;
final AtomicReference<GenericKafkaSender> kafkaSenderRef = new AtomicReference<>();
final CountDownLatch expectedCommandResponses = new CountDownLatch(1);
final VertxTestContext setup = new VertxTestContext();
final Checkpoint setupDone = setup.checkpoint();
final Checkpoint ttdReceivedPrecondition = setup.checkpoint();
final Future<MessageConsumer> kafkaAsyncErrorResponseConsumer = helper.createDeliveryFailureCommandResponseConsumer(ctx, tenantId, HttpURLConnection.HTTP_BAD_REQUEST, response -> {
ctx.verify(() -> {
DownstreamMessageAssertions.assertMessageContainsTimeToLive(response, TTL_COMMAND_RESPONSE);
});
expectedCommandResponses.countDown();
}, null);
connectToAdapter(tenantId, deviceId, password, () -> createEventConsumer(tenantId, msg -> {
// expect empty notification with TTD -1
setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
final TimeUntilDisconnectNotification notification = msg.getTimeUntilDisconnectNotification().orElse(null);
log.debug("received notification [{}]", notification);
setup.verify(() -> assertThat(notification).isNotNull());
if (notification.getTtd() == -1) {
ttdReceivedPrecondition.flag();
}
})).compose(con -> subscribeToCommands(endpointConfig, tenantId, commandTargetDeviceId).onSuccess(recv -> recv.handler((delivery, msg) -> ctx.failNow(new IllegalStateException("should not have received command"))))).compose(ok -> helper.createGenericKafkaSender().onSuccess(kafkaSenderRef::set).mapEmpty()).compose(v -> kafkaAsyncErrorResponseConsumer).onComplete(setup.succeeding(v -> setupDone.flag()));
assertWithMessage("setup of adapter finished within %s seconds", IntegrationTestSupport.getTestSetupTimeout()).that(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
final String commandTopic = new HonoTopic(HonoTopic.Type.COMMAND, tenantId).toString();
log.debug("sending command message lacking subject and correlation ID - no failure response expected here");
final Map<String, Object> properties1 = Map.of(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId, MessageHelper.SYS_PROPERTY_CONTENT_TYPE, MessageHelper.CONTENT_TYPE_OCTET_STREAM, KafkaRecordHelper.HEADER_RESPONSE_REQUIRED, true);
kafkaSenderRef.get().sendAndWaitForOutcome(commandTopic, tenantId, deviceId, Buffer.buffer(), properties1).onComplete(ctx.succeeding(ok -> {
}));
log.debug("sending command message lacking subject");
final String correlationId = "1";
final Map<String, Object> properties2 = Map.of(MessageHelper.SYS_PROPERTY_CORRELATION_ID, correlationId, MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId, MessageHelper.SYS_PROPERTY_CONTENT_TYPE, MessageHelper.CONTENT_TYPE_OCTET_STREAM, KafkaRecordHelper.HEADER_RESPONSE_REQUIRED, true);
kafkaSenderRef.get().sendAndWaitForOutcome(commandTopic, tenantId, deviceId, Buffer.buffer(), properties2).onComplete(ctx.succeeding(ok -> {
}));
final long timeToWait = 2500;
if (!expectedCommandResponses.await(timeToWait, TimeUnit.MILLISECONDS)) {
log.info("Timeout of {} milliseconds reached, stop waiting for command response", timeToWait);
}
kafkaAsyncErrorResponseConsumer.result().close().onComplete(ar -> {
if (expectedCommandResponses.getCount() == 0) {
ctx.completeNow();
} else {
ctx.failNow(new IllegalStateException("did not receive command response"));
}
});
}
Aggregations