Merge "Added STD sim 2.0.0 tests"
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / dmaap / DmaapMessageHandlerTest.java
index 09dbf92..f0efddc 100644 (file)
 
 package org.oransc.policyagent.dmaap;
 
+import static ch.qos.logback.classic.Level.WARN;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
 
 import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.Optional;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.onap.dmaap.mr.client.MRBatchingPublisher;
-import org.onap.dmaap.mr.client.response.MRPublisherResponse;
+import org.mockito.ArgumentCaptor;
 import org.oransc.policyagent.clients.AsyncRestClient;
-import org.oransc.policyagent.configuration.ApplicationConfig;
 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
+import org.oransc.policyagent.repository.ImmutablePolicyType;
+import org.oransc.policyagent.repository.PolicyType;
+import org.oransc.policyagent.utils.LoggingUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.reactive.function.client.WebClientResponseException;
 
 import reactor.core.publisher.Mono;
 import reactor.test.StepVerifier;
 
-public class DmaapMessageHandlerTest {
-
+class DmaapMessageHandlerTest {
+    private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandlerTest.class);
     private static final String URL = "url";
-    private static final String PAYLOAD = "payload";
 
-    private ApplicationConfig appConfig = mock(ApplicationConfig.class);
-    private final MRBatchingPublisher dmaapClient = mock(MRBatchingPublisher.class);
+    private final AsyncRestClient dmaapClient = mock(AsyncRestClient.class);
     private final AsyncRestClient agentClient = mock(AsyncRestClient.class);
     private DmaapMessageHandler testedObject;
     private static Gson gson = new GsonBuilder() //
-        .serializeNulls() //
         .create(); //
 
     @BeforeEach
@@ -62,16 +76,28 @@ public class DmaapMessageHandlerTest {
         testedObject = spy(new DmaapMessageHandler(dmaapClient, agentClient));
     }
 
+    static JsonObject payloadAsJson() {
+        return gson.fromJson(payloadAsString(), JsonObject.class);
+    }
+
+    static String payloadAsString() {
+        PolicyType pt = ImmutablePolicyType.builder().name("name").schema("schema").build();
+        return gson.toJson(pt);
+    }
+
     DmaapRequestMessage dmaapRequestMessage(Operation operation) {
-        return ImmutableDmaapRequestMessage.builder().apiVersion("apiVersion") //
+        Optional<JsonObject> payload =
+            ((operation == Operation.PUT || operation == Operation.POST) ? Optional.of(payloadAsJson())
+                : Optional.empty());
+        return ImmutableDmaapRequestMessage.builder() //
+            .apiVersion("apiVersion") //
             .correlationId("correlationId") //
             .operation(operation) //
             .originatorId("originatorId") //
-            .payload(PAYLOAD) //
+            .payload(payload) //
             .requestId("requestId") //
             .target("target") //
             .timestamp("timestamp") //
-            .type("type") //
             .url(URL) //
             .build();
     }
@@ -80,31 +106,69 @@ public class DmaapMessageHandlerTest {
         return gson.toJson(dmaapRequestMessage(operation));
     }
 
+    private Mono<ResponseEntity<String>> okResponse() {
+        ResponseEntity<String> entity = new ResponseEntity<>("OK", HttpStatus.OK);
+        return Mono.just(entity);
+    }
+
+    private Mono<ResponseEntity<String>> notOkResponse() {
+        ResponseEntity<String> entity = new ResponseEntity<>("NOK", HttpStatus.BAD_GATEWAY);
+        return Mono.just(entity);
+    }
+
+    @Test
+    void testMessageParsing() {
+        String message = dmaapInputMessage(Operation.DELETE);
+        logger.info(message);
+        DmaapRequestMessage parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
+        assertNotNull(parsedMessage);
+        assertFalse(parsedMessage.payload().isPresent());
+
+        message = dmaapInputMessage(Operation.PUT);
+        logger.info(message);
+        parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
+        assertNotNull(parsedMessage);
+        assertTrue(parsedMessage.payload().isPresent());
+    }
+
     @Test
-    public void successfulDelete() throws IOException {
-        doReturn(Mono.just("OK")).when(agentClient).delete(anyString());
-        doReturn(1).when(dmaapClient).send(anyString());
-        doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
+    void unparseableMessage_thenWarning() {
+        final ListAppender<ILoggingEvent> logAppender =
+            LoggingUtils.getLogListAppender(DmaapMessageHandler.class, WARN);
+
+        String msg = "bad message";
+        testedObject.handleDmaapMsg(msg);
+
+        assertThat(logAppender.list.get(0).getFormattedMessage()).startsWith(
+            "handleDmaapMsg failure org.oransc.policyagent.exceptions.ServiceException: Received unparsable "
+                + "message from DMAAP: \"" + msg + "\", reason: ");
+    }
+
+    @Test
+    void successfulDelete() throws IOException {
+        doReturn(okResponse()).when(agentClient).deleteForEntity(anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
+
+        String message = dmaapInputMessage(Operation.DELETE);
 
         StepVerifier //
-            .create(testedObject.createTask(dmaapInputMessage(Operation.DELETE))) //
+            .create(testedObject.createTask(message)) //
             .expectSubscription() //
             .expectNext("OK") //
             .verifyComplete(); //
 
-        verify(agentClient, times(1)).delete(URL);
+        verify(agentClient).deleteForEntity(URL);
         verifyNoMoreInteractions(agentClient);
 
-        verify(dmaapClient, times(1)).send(anyString());
-        verify(dmaapClient, times(1)).sendBatchWithResponse();
+        verify(dmaapClient).post(anyString(), anyString());
+
         verifyNoMoreInteractions(dmaapClient);
     }
 
     @Test
-    public void successfulGet() throws IOException {
-        doReturn(Mono.just("OK")).when(agentClient).get(anyString());
-        doReturn(1).when(dmaapClient).send(anyString());
-        doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
+    void successfulGet() throws IOException {
+        doReturn(okResponse()).when(agentClient).getForEntity(anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
 
         StepVerifier //
             .create(testedObject.createTask(dmaapInputMessage(Operation.GET))) //
@@ -112,19 +176,37 @@ public class DmaapMessageHandlerTest {
             .expectNext("OK") //
             .verifyComplete(); //
 
-        verify(agentClient, times(1)).get(URL);
+        verify(agentClient).getForEntity(URL);
         verifyNoMoreInteractions(agentClient);
 
-        verify(dmaapClient, times(1)).send(anyString());
-        verify(dmaapClient, times(1)).sendBatchWithResponse();
+        verify(dmaapClient).post(anyString(), anyString());
         verifyNoMoreInteractions(dmaapClient);
     }
 
     @Test
-    public void successfulPut() throws IOException {
-        doReturn(Mono.just("OK")).when(agentClient).put(anyString(), anyString());
-        doReturn(1).when(dmaapClient).send(anyString());
-        doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
+    void exceptionFromAgentWhenGet_thenPostError() throws IOException {
+        String errorBody = "Unavailable";
+        WebClientResponseException webClientResponseException = new WebClientResponseException(
+            HttpStatus.SERVICE_UNAVAILABLE.value(), "", (HttpHeaders) null, errorBody.getBytes(), (Charset) null);
+        doReturn(Mono.error(webClientResponseException)).when(agentClient).getForEntity(anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
+
+        StepVerifier //
+            .create(testedObject.createTask(dmaapInputMessage(Operation.GET))) //
+            .expectSubscription() //
+            .verifyComplete(); //
+
+        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
+        verify(dmaapClient).post(anyString(), captor.capture());
+        String actualMessage = captor.getValue();
+        assertThat(actualMessage).contains(HttpStatus.SERVICE_UNAVAILABLE.toString()) //
+            .contains(errorBody);
+    }
+
+    @Test
+    void successfulPut() throws IOException {
+        doReturn(okResponse()).when(agentClient).putForEntity(anyString(), anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
 
         StepVerifier //
             .create(testedObject.createTask(dmaapInputMessage(Operation.PUT))) //
@@ -132,19 +214,17 @@ public class DmaapMessageHandlerTest {
             .expectNext("OK") //
             .verifyComplete(); //
 
-        verify(agentClient, times(1)).put(URL, PAYLOAD);
+        verify(agentClient).putForEntity(URL, payloadAsString());
         verifyNoMoreInteractions(agentClient);
 
-        verify(dmaapClient, times(1)).send(anyString());
-        verify(dmaapClient, times(1)).sendBatchWithResponse();
+        verify(dmaapClient).post(anyString(), anyString());
         verifyNoMoreInteractions(dmaapClient);
     }
 
     @Test
-    public void successfulPost() throws IOException {
-        doReturn(Mono.just("OK")).when(agentClient).post(anyString(), anyString());
-        doReturn(1).when(dmaapClient).send(anyString());
-        doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
+    void successfulPost() throws IOException {
+        doReturn(okResponse()).when(agentClient).postForEntity(anyString(), anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
 
         StepVerifier //
             .create(testedObject.createTask(dmaapInputMessage(Operation.POST))) //
@@ -152,31 +232,59 @@ public class DmaapMessageHandlerTest {
             .expectNext("OK") //
             .verifyComplete(); //
 
-        verify(agentClient, times(1)).post(URL, PAYLOAD);
+        verify(agentClient).postForEntity(URL, payloadAsString());
         verifyNoMoreInteractions(agentClient);
 
-        verify(dmaapClient, times(1)).send(anyString());
-        verify(dmaapClient, times(1)).sendBatchWithResponse();
+        verify(dmaapClient).post(anyString(), anyString());
         verifyNoMoreInteractions(dmaapClient);
     }
 
     @Test
-    public void errorCase() throws IOException {
-        doReturn(Mono.error(new Exception("Refused"))).when(agentClient).put(anyString(), anyString());
-        doReturn(1).when(dmaapClient).send(anyString());
-        doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
-        StepVerifier //
-            .create(testedObject.createTask(dmaapInputMessage(Operation.PUT))) //
-            .expectSubscription() //
-            .verifyComplete(); //
+    void exceptionWhenCallingPolicyAgent_thenNotFoundResponse() throws IOException {
 
-        verify(agentClient, times(1)).put(URL, PAYLOAD);
+        doReturn(notOkResponse()).when(agentClient).putForEntity(anyString(), anyString());
+        doReturn(Mono.just("OK")).when(dmaapClient).post(anyString(), anyString());
+
+        testedObject.createTask(dmaapInputMessage(Operation.PUT)).block();
+
+        verify(agentClient).putForEntity(anyString(), anyString());
         verifyNoMoreInteractions(agentClient);
 
-        // Error response
-        verify(dmaapClient, times(1)).send(anyString());
-        verify(dmaapClient, times(1)).sendBatchWithResponse();
+        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
+        verify(dmaapClient).post(anyString(), captor.capture());
+        String actualMessage = captor.getValue();
+        assertThat(actualMessage).as("Message \"%s\" sent to DMaaP contains %s", actualMessage, HttpStatus.BAD_GATEWAY)
+            .contains(HttpStatus.BAD_GATEWAY.toString());
+
         verifyNoMoreInteractions(dmaapClient);
     }
 
+    @Test
+    void unsupportedOperationInMessage_thenNotFoundResponseWithNotImplementedOperation() throws Exception {
+        String message = dmaapInputMessage(Operation.PUT).toString();
+        String badOperation = "BAD";
+        message = message.replace(Operation.PUT.toString(), badOperation);
+
+        testedObject.handleDmaapMsg(message);
+
+        ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
+        verify(dmaapClient).post(anyString(), captor.capture());
+        String actualMessage = captor.getValue();
+        assertThat(actualMessage).contains("Not implemented operation") //
+            .contains("BAD_REQUEST");
+    }
+
+    @Test
+    void putWithoutPayload_thenNotFoundResponseWithWarning() throws Exception {
+        String message = dmaapInputMessage(Operation.PUT).toString();
+        message = message.replace(",\"payload\":{\"name\":\"name\",\"schema\":\"schema\"}", "");
+
+        final ListAppender<ILoggingEvent> logAppender =
+            LoggingUtils.getLogListAppender(DmaapMessageHandler.class, WARN);
+
+        testedObject.handleDmaapMsg(message);
+
+        assertThat(logAppender.list.get(0).getFormattedMessage())
+            .startsWith("Expected payload in message from DMAAP: ");
+    }
 }