Remove Sonar warnings
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / dmaap / DmaapMessageHandlerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.oransc.policyagent.dmaap;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.anyString;
29 import static org.mockito.Mockito.doReturn;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.spy;
32 import static org.mockito.Mockito.verify;
33 import static org.mockito.Mockito.verifyNoMoreInteractions;
34
35 import ch.qos.logback.classic.Level;
36 import ch.qos.logback.classic.spi.ILoggingEvent;
37 import ch.qos.logback.core.read.ListAppender;
38
39 import com.google.gson.Gson;
40 import com.google.gson.GsonBuilder;
41 import com.google.gson.JsonObject;
42
43 import java.io.IOException;
44 import java.util.Optional;
45
46 import org.junit.jupiter.api.BeforeEach;
47 import org.junit.jupiter.api.Test;
48 import org.mockito.ArgumentCaptor;
49 import org.onap.dmaap.mr.client.MRBatchingPublisher;
50 import org.onap.dmaap.mr.client.response.MRPublisherResponse;
51 import org.oransc.policyagent.clients.AsyncRestClient;
52 import org.oransc.policyagent.dmaap.DmaapRequestMessage.Operation;
53 import org.oransc.policyagent.repository.ImmutablePolicyType;
54 import org.oransc.policyagent.repository.PolicyType;
55 import org.oransc.policyagent.utils.LoggingUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.web.reactive.function.client.WebClientResponseException;
61
62 import reactor.core.publisher.Mono;
63 import reactor.test.StepVerifier;
64
65 class DmaapMessageHandlerTest {
66     private static final Logger logger = LoggerFactory.getLogger(DmaapMessageHandlerTest.class);
67     private static final String URL = "url";
68
69     private final MRBatchingPublisher dmaapClient = mock(MRBatchingPublisher.class);
70     private final AsyncRestClient agentClient = mock(AsyncRestClient.class);
71     private DmaapMessageHandler testedObject;
72     private static Gson gson = new GsonBuilder() //
73         .create(); //
74
75     @BeforeEach
76     private void setUp() throws Exception {
77         testedObject = spy(new DmaapMessageHandler(dmaapClient, agentClient));
78     }
79
80     static JsonObject payloadAsJson() {
81         return gson.fromJson(payloadAsString(), JsonObject.class);
82     }
83
84     static String payloadAsString() {
85         PolicyType pt = ImmutablePolicyType.builder().name("name").schema("schema").build();
86         return gson.toJson(pt);
87     }
88
89     DmaapRequestMessage dmaapRequestMessage(Operation operation) {
90         Optional<JsonObject> payload =
91             ((operation == Operation.PUT || operation == Operation.POST) ? Optional.of(payloadAsJson())
92                 : Optional.empty());
93         return ImmutableDmaapRequestMessage.builder() //
94             .apiVersion("apiVersion") //
95             .correlationId("correlationId") //
96             .operation(operation) //
97             .originatorId("originatorId") //
98             .payload(payload) //
99             .requestId("requestId") //
100             .target("target") //
101             .timestamp("timestamp") //
102             .url(URL) //
103             .build();
104     }
105
106     private String dmaapInputMessage(Operation operation) {
107         return gson.toJson(dmaapRequestMessage(operation));
108     }
109
110     private Mono<ResponseEntity<String>> okResponse() {
111         ResponseEntity<String> entity = new ResponseEntity<>("OK", HttpStatus.OK);
112         return Mono.just(entity);
113     }
114
115     @Test
116     void testMessageParsing() {
117         String message = dmaapInputMessage(Operation.DELETE);
118         logger.info(message);
119         DmaapRequestMessage parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
120         assertNotNull(parsedMessage);
121         assertFalse(parsedMessage.payload().isPresent());
122
123         message = dmaapInputMessage(Operation.PUT);
124         logger.info(message);
125         parsedMessage = gson.fromJson(message, ImmutableDmaapRequestMessage.class);
126         assertNotNull(parsedMessage);
127         assertTrue(parsedMessage.payload().isPresent());
128     }
129
130     @Test
131     void unparseableMessage_thenWarning() {
132         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DmaapMessageHandler.class);
133
134         testedObject.handleDmaapMsg("bad message");
135
136         assertThat(logAppender.list.get(0).getLevel()).isEqualTo(Level.WARN);
137         assertThat(logAppender.list.toString().contains("handleDmaapMsg failure ")).isTrue();
138     }
139
140     @Test
141     void successfulDelete() throws IOException {
142         doReturn(okResponse()).when(agentClient).deleteForEntity(anyString());
143         doReturn(1).when(dmaapClient).send(anyString());
144         doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
145
146         String message = dmaapInputMessage(Operation.DELETE);
147
148         StepVerifier //
149             .create(testedObject.createTask(message)) //
150             .expectSubscription() //
151             .expectNext("OK") //
152             .verifyComplete(); //
153
154         verify(agentClient).deleteForEntity(URL);
155         verifyNoMoreInteractions(agentClient);
156
157         verify(dmaapClient).send(anyString());
158         verify(dmaapClient).sendBatchWithResponse();
159         verifyNoMoreInteractions(dmaapClient);
160     }
161
162     @Test
163     void successfulGet() throws IOException {
164         doReturn(okResponse()).when(agentClient).getForEntity(anyString());
165         doReturn(1).when(dmaapClient).send(anyString());
166         doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
167
168         StepVerifier //
169             .create(testedObject.createTask(dmaapInputMessage(Operation.GET))) //
170             .expectSubscription() //
171             .expectNext("OK") //
172             .verifyComplete(); //
173
174         verify(agentClient).getForEntity(URL);
175         verifyNoMoreInteractions(agentClient);
176
177         verify(dmaapClient).send(anyString());
178         verify(dmaapClient).sendBatchWithResponse();
179         verifyNoMoreInteractions(dmaapClient);
180     }
181
182     @Test
183     void successfulPut() throws IOException {
184         doReturn(okResponse()).when(agentClient).putForEntity(anyString(), anyString());
185         doReturn(1).when(dmaapClient).send(anyString());
186         doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
187
188         StepVerifier //
189             .create(testedObject.createTask(dmaapInputMessage(Operation.PUT))) //
190             .expectSubscription() //
191             .expectNext("OK") //
192             .verifyComplete(); //
193
194         verify(agentClient).putForEntity(URL, payloadAsString());
195         verifyNoMoreInteractions(agentClient);
196
197         verify(dmaapClient).send(anyString());
198         verify(dmaapClient).sendBatchWithResponse();
199         verifyNoMoreInteractions(dmaapClient);
200     }
201
202     @Test
203     void successfulPost() throws IOException {
204         doReturn(okResponse()).when(agentClient).postForEntity(anyString(), anyString());
205         doReturn(1).when(dmaapClient).send(anyString());
206         doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
207
208         StepVerifier //
209             .create(testedObject.createTask(dmaapInputMessage(Operation.POST))) //
210             .expectSubscription() //
211             .expectNext("OK") //
212             .verifyComplete(); //
213
214         verify(agentClient).postForEntity(URL, payloadAsString());
215         verifyNoMoreInteractions(agentClient);
216
217         verify(dmaapClient).send(anyString());
218         verify(dmaapClient).sendBatchWithResponse();
219         verifyNoMoreInteractions(dmaapClient);
220     }
221
222     @Test
223     void exceptionWhenCallingPolicyAgent_thenNotFoundResponse() throws IOException {
224         WebClientResponseException except = new WebClientResponseException(400, "Refused", null, null, null, null);
225         doReturn(Mono.error(except)).when(agentClient).putForEntity(anyString(), any());
226         doReturn(1).when(dmaapClient).send(anyString());
227         doReturn(new MRPublisherResponse()).when(dmaapClient).sendBatchWithResponse();
228
229         StepVerifier //
230             .create(testedObject.createTask(dmaapInputMessage(Operation.PUT))) //
231             .expectSubscription() //
232             .verifyComplete(); //
233
234         verify(agentClient).putForEntity(anyString(), anyString());
235         verifyNoMoreInteractions(agentClient);
236
237         ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
238         verify(dmaapClient).send(captor.capture());
239         String actualMessage = captor.getValue();
240         assertThat(actualMessage.contains(HttpStatus.BAD_REQUEST.toString())).isTrue();
241
242         verify(dmaapClient).sendBatchWithResponse();
243         verifyNoMoreInteractions(dmaapClient);
244     }
245
246     @Test
247     void unsupportedOperationInMessage_thenNotFoundResponseWithNotImplementedOperation() throws Exception {
248         String message = dmaapInputMessage(Operation.PUT).toString();
249         String badOperation = "BAD";
250         message = message.replace(Operation.PUT.toString(), badOperation);
251
252         testedObject.handleDmaapMsg(message);
253
254         ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
255         verify(dmaapClient).send(captor.capture());
256         String actualMessage = captor.getValue();
257         assertThat(actualMessage
258             .contains(HttpStatus.BAD_REQUEST + "\",\"message\":\"Not implemented operation: " + badOperation)).isTrue();
259
260         verify(dmaapClient).sendBatchWithResponse();
261         verifyNoMoreInteractions(dmaapClient);
262     }
263
264     @Test
265     void putWithoutPayload_thenNotFoundResponseWithWarning() throws Exception {
266         String message = dmaapInputMessage(Operation.PUT).toString();
267         message = message.replace(",\"payload\":{\"name\":\"name\",\"schema\":\"schema\"}", "");
268
269         final ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DmaapMessageHandler.class);
270
271         testedObject.handleDmaapMsg(message);
272
273         assertThat(logAppender.list.get(0).getLevel()).isEqualTo(Level.WARN);
274         assertThat(logAppender.list.toString().contains("Expected payload in message from DMAAP: ")).isTrue();
275     }
276 }