use of org.mockito.Mockito.RETURNS_SELF in project hono by eclipse.
the class HttpBasedMessageMappingTest method testMapCommandSucceeds.
/**
* Verifies that the result returned by the upstream mapping service contains the
* mapped payload.
*
* @param ctx The helper to use for running tests on vert.x.
*/
@SuppressWarnings("unchecked")
@Test
public void testMapCommandSucceeds(final VertxTestContext ctx) {
config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
final Buffer payload = Buffer.buffer("payload");
final Buffer responseBody = Buffer.buffer("changed");
final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
when(httpResponse.bodyAsBuffer()).thenReturn(responseBody);
when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_OK);
when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
final Command command = mock(Command.class);
when(command.getPayload()).thenReturn(payload);
final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setUpstreamMessageMapper("mapper");
messageMapping.mapUpstreamMessage(assertion, command).onComplete(ctx.succeeding(mappedBuffer -> {
ctx.verify(() -> {
assertThat(mappedBuffer).isEqualTo(responseBody);
verify(mapperWebClient, times(1)).post(anyInt(), anyString(), anyString());
});
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
}
use of org.mockito.Mockito.RETURNS_SELF in project hono by eclipse.
the class HttpBasedMessageMappingTest method testMapMessageSucceeds.
/**
* Verifies that the result returned by the mapping service contains the
* mapped payload, device ID and additional properties.
*
* @param ctx The helper to use for running tests on vert.x.
*/
@SuppressWarnings("unchecked")
@Test
public void testMapMessageSucceeds(final VertxTestContext ctx) {
config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
final String newDeviceId = "new-device";
final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
final MultiMap responseHeaders = MultiMap.caseInsensitiveMultiMap();
responseHeaders.add(MessageHelper.APP_PROPERTY_DEVICE_ID, newDeviceId);
responseHeaders.add("foo", "bar");
final Buffer responseBody = Buffer.buffer("changed");
final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
when(httpResponse.headers()).thenReturn(responseHeaders);
when(httpResponse.bodyAsBuffer()).thenReturn(responseBody);
when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_OK);
when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
final String topic = String.format("%s/?content-type=%s", TelemetryConstants.TELEMETRY_ENDPOINT, URLEncoder.encode("text/plain", StandardCharsets.UTF_8));
final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, topic);
final MqttContext context = newContext(message, span, new Device(TEST_TENANT_ID, "gateway"));
final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setDownstreamMessageMapper("mapper");
messageMapping.mapDownstreamMessage(context, targetAddress, assertion).onComplete(ctx.succeeding(mappedMessage -> {
ctx.verify(() -> {
assertThat(mappedMessage.getTargetAddress().getResourceId()).isEqualTo("new-device");
assertThat(mappedMessage.getPayload()).isEqualTo(responseBody);
assertThat(mappedMessage.getAdditionalProperties()).doesNotContainKey(MessageHelper.APP_PROPERTY_DEVICE_ID);
assertThat(mappedMessage.getAdditionalProperties()).containsEntry("foo", "bar");
});
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
final ArgumentCaptor<MultiMap> headersCaptor = ArgumentCaptor.forClass(MultiMap.class);
verify(httpRequest).putHeaders(headersCaptor.capture());
final MultiMap addedHeaders = headersCaptor.getValue();
assertThat(addedHeaders.contains(MessageHelper.APP_PROPERTY_ORIG_ADDRESS, topic, false)).isTrue();
assertThat(addedHeaders.contains(HttpHeaders.CONTENT_TYPE.toString(), "text/plain", false));
}
use of org.mockito.Mockito.RETURNS_SELF in project hono by eclipse.
the class HttpBasedMessageMappingTest method testMappingFailsForWhenPayloadCannotMapped.
/**
* Verifies that the downstream mapper returns a failed future with a ServerErrorException if the downstream mapper has been configured
* for an adapter but the remote service returns a 403 status code indicating that the device payload cannot be mapped.
*
* @param ctx The Vert.x test context.
*/
@Test
@SuppressWarnings("unchecked")
public void testMappingFailsForWhenPayloadCannotMapped(final VertxTestContext ctx) {
config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN);
when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, "mqtt-topic");
final MqttContext context = newContext(message, span, new Device(TEST_TENANT_ID, "gateway"));
final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setDownstreamMessageMapper("mapper");
messageMapping.mapDownstreamMessage(context, targetAddress, assertion).onComplete(ctx.failing(t -> {
ctx.verify(() -> {
assertThat(t).isInstanceOf(ServerErrorException.class);
assertThat((((ServerErrorException) t).getErrorCode())).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE);
});
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handlerCaptor = VertxMockSupport.argumentCaptorHandler();
verify(httpRequest).sendBuffer(any(Buffer.class), handlerCaptor.capture());
handlerCaptor.getValue().handle(Future.succeededFuture(httpResponse));
}
use of org.mockito.Mockito.RETURNS_SELF in project hono by eclipse.
the class HttpBasedMessageMappingTest method testMappingCommandFailsForWhenPayloadCannotMapped.
/**
* Verifies that the upstream mapper returns a failed future with a ServerErrorException if the upstream mapper has been configured
* for an adapter but the remote service returns a 403 status code indicating that the device payload cannot be mapped.
*
* @param ctx The Vert.x test context.
*/
@Test
@SuppressWarnings("unchecked")
public void testMappingCommandFailsForWhenPayloadCannotMapped(final VertxTestContext ctx) {
config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
final Buffer payload = Buffer.buffer("payload");
final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN);
when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
final Command command = mock(Command.class);
when(command.getPayload()).thenReturn(payload);
final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setUpstreamMessageMapper("mapper");
messageMapping.mapUpstreamMessage(assertion, command).onComplete(ctx.failing(t -> {
ctx.verify(() -> {
assertThat(t).isInstanceOf(ServerErrorException.class);
assertThat((((ServerErrorException) t).getErrorCode())).isEqualTo(HttpURLConnection.HTTP_UNAVAILABLE);
});
ctx.completeNow();
}));
final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
}
use of org.mockito.Mockito.RETURNS_SELF in project hono by eclipse.
the class LoraProtocolAdapterTest method setUp.
/**
* Sets up the fixture.
*/
@BeforeEach
public void setUp() {
vertx = mock(Vertx.class);
final Context context = VertxMockSupport.mockContext(vertx);
webClient = mock(WebClient.class);
this.properties = givenDefaultConfigurationProperties();
createClients();
prepareClients();
processMessageSpan = mock(Span.class);
when(processMessageSpan.context()).thenReturn(mock(SpanContext.class));
final Span otherSpan = mock(Span.class);
when(otherSpan.context()).thenReturn(mock(SpanContext.class));
final SpanBuilder processMessageSpanBuilder = mock(SpanBuilder.class, withSettings().defaultAnswer(RETURNS_SELF));
when(processMessageSpanBuilder.start()).thenReturn(processMessageSpan);
final SpanBuilder otherSpanBuilder = mock(SpanBuilder.class, withSettings().defaultAnswer(RETURNS_SELF));
when(otherSpanBuilder.start()).thenReturn(otherSpan);
final Tracer tracer = mock(Tracer.class);
when(tracer.buildSpan(eq(LoraProtocolAdapter.SPAN_NAME_PROCESS_MESSAGE))).thenReturn(processMessageSpanBuilder);
when(tracer.buildSpan(argThat(opName -> !opName.equals(LoraProtocolAdapter.SPAN_NAME_PROCESS_MESSAGE)))).thenReturn(otherSpanBuilder);
final HttpAdapterMetrics metrics = mock(HttpAdapterMetrics.class);
when(metrics.startTimer()).thenReturn(mock(Sample.class));
adapter = new LoraProtocolAdapter(webClient);
adapter.setConfig(properties);
adapter.setTracer(tracer);
adapter.init(vertx, context);
adapter.setMetrics(metrics);
setServiceClients(adapter);
}
Aggregations