Sonar Critical Fix
[dcaegen2/analytics/tca.git] / dcae-analytics-dmaap / src / test / java / org / onap / dcae / apod / analytics / dmaap / service / BaseDMaaPMRComponentTest.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *   You may obtain a copy of the License at
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============================LICENSE_END===========================================
19  */
20
21 package org.onap.dcae.apod.analytics.dmaap.service;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.google.common.base.Optional;
25 import org.apache.commons.lang3.tuple.Pair;
26 import org.apache.http.HttpEntity;
27 import org.apache.http.HttpResponse;
28 import org.apache.http.StatusLine;
29 import org.apache.http.client.ResponseHandler;
30 import org.junit.Rule;
31 import org.junit.Test;
32 import org.junit.rules.ExpectedException;
33 import org.mockito.Mockito;
34 import org.onap.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
35 import org.onap.dcae.apod.analytics.dmaap.BaseAnalyticsDMaaPUnitTest;
36 import org.onap.dcae.apod.analytics.dmaap.domain.config.DMaaPMRPublisherConfig;
37 import org.onap.dcae.apod.analytics.dmaap.domain.config.DMaaPMRSubscriberConfig;
38 import org.onap.dcae.apod.analytics.dmaap.domain.response.DMaaPMRSubscriberResponse;
39 import org.onap.dcae.apod.analytics.dmaap.service.publisher.DMaaPMRPublisherQueue;
40
41 import java.io.IOException;
42 import java.net.URI;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.List;
46
47 import static org.hamcrest.Matchers.containsInAnyOrder;
48 import static org.hamcrest.Matchers.hasSize;
49 import static org.hamcrest.Matchers.is;
50 import static org.hamcrest.Matchers.isA;
51 import static org.junit.Assert.assertEquals;
52 import static org.junit.Assert.assertFalse;
53 import static org.junit.Assert.assertThat;
54 import static org.junit.Assert.assertTrue;
55 import static org.mockito.BDDMockito.given;
56 import static org.mockito.Mockito.mock;
57
58 /**
59  * @author Manjesh Gowda. Creation Date: 11/4/2016.
60  */
61 public class BaseDMaaPMRComponentTest extends BaseAnalyticsDMaaPUnitTest {
62
63     @Test
64     public void testGetAuthHeaderWithGoodValues() {
65         String expectedEncodedString = "Basic bTAwNTAyQHRjYS5hZi5kY2FlLmNvbTpUZTUwMjFhYmM=";
66         Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader("USER", "PASSWORD");
67         assertTrue(" Authentication Header has value ", actualOutput.isPresent());
68 //        assertEquals(" Authentication Header has value ", expectedEncodedString, actualOutput.get());
69     }
70
71     @Test
72     public void testGetAuthHeaderWithNullValues() {
73         Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader(null, null);
74         assertFalse(" Authentication Header has value ", actualOutput.isPresent());
75     }
76
77     @Test
78     public void testGetAuthHeaderWithUserNullValue() {
79         Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader("USER", null);
80         assertFalse(" Authentication Header has value ", actualOutput.isPresent());
81     }
82
83     @Test
84     public void testGetAuthHeaderWithPasswordNullValue() {
85         Optional<String> actualOutput = BaseDMaaPMRComponent.getAuthHeader(null, "PASSWORD");
86         assertFalse(" Authentication Header has value ", actualOutput.isPresent());
87     }
88
89     @Test
90     public void testCreatePublishURIWithGoodValues() {
91         URI actualURI = BaseDMaaPMRComponent.createPublisherURI(getPublisherConfig());
92         String test = actualURI.toString();
93         assertEquals("Generated Publisher URL is correct",
94                 "https://testHostName:8080/events/testTopicName", actualURI.toString());
95     }
96
97     @Test(expected = DCAEAnalyticsRuntimeException.class)
98     public void testCreatePublishURIWithURISyntaxException() {
99         DMaaPMRPublisherConfig badPublisherConfig = new DMaaPMRPublisherConfig
100                 .Builder(" dav /gh. ss/ asd ", "///@$%#-htps:<>!##")
101                 .setPortNumber(0)
102                 .setProtocol("https").build();
103
104       BaseDMaaPMRComponent.createPublisherURI(badPublisherConfig);
105     }
106
107     @Test
108     public void testCreateSubscribeURIWithGoodValues() {
109         URI actualURI = BaseDMaaPMRComponent.createSubscriberURI(
110                 getSubscriberConfig("test-consumer-group", "test-consumer-id"));
111         assertEquals("Generated Subscriber URL is correct",
112                 "https://testHostName:8080/events/testTopicName/" +
113                         "test-consumer-id/test-consumer-group?timeout=2000&limit=20",
114                 actualURI.toString());
115     }
116
117     @Test(expected = DCAEAnalyticsRuntimeException.class)
118     public void testCreateSubscribeURIWithURISyntaxException() {
119         DMaaPMRSubscriberConfig badSubscriberConfig = new DMaaPMRSubscriberConfig
120                 .Builder(" dav /gh. ss/ asd ", "")
121                 .setPortNumber(PORT_NUMBER)
122                 .setProtocol(HTTP_PROTOCOL)
123                 .setContentType(CONTENT_TYPE).build();
124
125         URI actualURI = BaseDMaaPMRComponent.createSubscriberURI(badSubscriberConfig);
126     }
127
128     @Test
129     public void testConvertToJsonStringGoodJsonStringList() {
130         List<String> jsonMessage = Arrays.asList(
131                 "{\"message\":\"I'm Object 1 Message\"}",
132                 "{\"message\":\"I'm Object 2 Message\"}");
133
134         String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(jsonMessage);
135
136         String expectedJSONMsg = "[{\"message\":\"I'm Object 1 Message\"}," +
137                 "{\"message\":\"I'm Object 2 Message\"}]";
138         assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);
139
140     }
141
142     @Rule
143     public ExpectedException expectedJsonProcessingException = ExpectedException.none();
144
145     @Test
146     public void testConvertToJsonStringBadJsonStringList() {
147         expectedJsonProcessingException.expect(DCAEAnalyticsRuntimeException.class);
148         expectedJsonProcessingException.expectCause(isA(JsonProcessingException.class));
149
150         List<String> jsonMessage = Arrays.asList(
151                 "{\"message\":\"I'm Object 1 Message\"",
152                 "\"message\":\"I'm Object 2 Message\"");
153
154         BaseDMaaPMRComponent.convertToJsonString(jsonMessage);
155     }
156
157     @Test
158     public void testConvertToJsonStringWithEmptyList() {
159         List<String> jsonMessage = Arrays.asList();
160         String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(jsonMessage);
161         String expectedJSONMsg = "[]";
162         assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);
163     }
164
165     @Test
166     public void testConvertToJsonStringWithNullList() {
167         String actualJSONMsg = BaseDMaaPMRComponent.convertToJsonString(null);
168         String expectedJSONMsg = "[]";
169         assertEquals("Convert a List of Strings to JSON is working fine", expectedJSONMsg, actualJSONMsg);
170     }
171
172
173     @Test
174     public void testConvertJsonToStringMessagesGoodValues() {
175         String inputJSONMsg = "[{\"message\":\"I'm Object 1 Message\"}," +
176                 "{\"message\":\"I'm Object 2 Message\"}]";
177         List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
178         assertThat(actualList, hasSize(2));
179         assertThat(actualList, containsInAnyOrder(
180                 "{\"message\":\"I'm Object 1 Message\"}",
181                 "{\"message\":\"I'm Object 2 Message\"}"
182         ));
183     }
184
185     @Test
186     public void testConvertJsonToStringMessagesNoValues() {
187         String inputJSONMsg = "[]";
188         List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
189         assertThat(actualList, hasSize(0));
190     }
191
192     @Test
193     public void testConvertJsonToStringMessagesNullValues() {
194         List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(null);
195         assertThat(actualList, hasSize(0));
196     }
197
198     @Test
199     public void testConvertJsonToStringMessagesEmptyValues() {
200         List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages("  ");
201         assertThat(actualList, hasSize(0));
202     }
203
204     @Rule
205     public ExpectedException convertToJSONIOException = ExpectedException.none();
206
207     @Test
208     public void testConvertJsonToStringMessagesException() {
209         convertToJSONIOException.expect(DCAEAnalyticsRuntimeException.class);
210         convertToJSONIOException.expectCause(isA(IOException.class));
211
212         String inputJSONMsg = "[\"{\"message\":\"I'm Object 1 Message\"}\"," +
213                 "\"{\"message\":\"I'm Object 2 Message\"}\"]";
214         List<String> actualList = BaseDMaaPMRComponent.convertJsonToStringMessages(inputJSONMsg);
215         assertThat(actualList, hasSize(2));
216         assertThat(actualList, containsInAnyOrder(
217                 "{\"message\":\"I'm Object 1 Message\"}",
218                 "{\"message\":\"I'm Object 2 Message\"}"
219         ));
220     }
221
222     @Test
223     public void testAddMessagesToRecoveryQueueAllGood() {
224         DMaaPMRPublisherQueue dmaapMRPublisherQueue = mock(DMaaPMRPublisherQueue.class);
225         given(dmaapMRPublisherQueue.addRecoverableMessages(Mockito.<String>anyList())).willReturn(0);
226         given(dmaapMRPublisherQueue.getBatchQueueRemainingSize()).willReturn(0);
227         List<String> messages = new ArrayList<String>();
228         BaseDMaaPMRComponent.addMessagesToRecoveryQueue(dmaapMRPublisherQueue, messages);
229     }
230
231     @Rule
232     public ExpectedException addQueueIllegalException = ExpectedException.none();
233
234     @Test
235     public void testAddMessagesToRecoveryQueueException() {
236         addQueueIllegalException.expect(isA(DCAEAnalyticsRuntimeException.class));
237         addQueueIllegalException.expectCause(isA(IllegalStateException.class));
238
239         DMaaPMRPublisherQueue dmaapMRPublisherQueue = mock(DMaaPMRPublisherQueue.class);
240
241         given(dmaapMRPublisherQueue.addRecoverableMessages(Mockito.<String>anyList()))
242                 .willThrow(IllegalStateException.class);
243         List<String> messages = new ArrayList<String>();
244
245         BaseDMaaPMRComponent.addMessagesToRecoveryQueue(dmaapMRPublisherQueue, messages);
246     }
247
248
249     @Test
250     public void testResponseHandler() {
251         HttpResponse mockHttpResponse = mock(HttpResponse.class);
252         StatusLine mockStatusLine = mock(StatusLine.class);
253         HttpEntity mockHttpEntity = mock(HttpEntity.class);
254         // Could not mock EntityUtils as it's final class
255         //EntityUtils mockEntityUtils = mock(EntityUtils.class);
256
257         given(mockHttpResponse.getStatusLine()).willReturn(mockStatusLine);
258         given(mockStatusLine.getStatusCode()).willReturn(200);
259         given(mockHttpResponse.getEntity()).willReturn(null);
260         //given(mockEntityUtils.toString()).willReturn("Test value");
261
262         ResponseHandler<Pair<Integer, String>> responseHandler = BaseDMaaPMRComponent.responseHandler();
263         try {
264             Pair<Integer, String> mappedResponse = responseHandler.handleResponse(mockHttpResponse);
265             assertTrue("Http response code returned properly ", mappedResponse.getLeft().equals(200));
266             assertTrue("Http response body returned properly ", mappedResponse.getRight().equals(""));
267         } catch (IOException e) {
268             e.printStackTrace();
269         }
270     }
271
272
273     @Test
274     public void testCreateSubscriberResponse() {
275         DMaaPMRSubscriberResponse dmaapMRSubscriberResponse =
276                 BaseDMaaPMRComponent.createSubscriberResponse(200, "Test Message", getTwoSampleMessages());
277
278         assertThat(dmaapMRSubscriberResponse.getResponseCode(), is(200));
279         assertEquals(dmaapMRSubscriberResponse.getResponseMessage(), "Test Message");
280         assertThat(dmaapMRSubscriberResponse.getFetchedMessages().size(), is(2));
281
282     }
283
284     @Test
285     public void testCreateSubscriberResponse_no_message() {
286         DMaaPMRSubscriberResponse dmaapMRSubscriberResponse =
287                 BaseDMaaPMRComponent.createSubscriberResponse(200, "Test Message", null);
288
289         assertThat(dmaapMRSubscriberResponse.getResponseCode(), is(200));
290         assertEquals(dmaapMRSubscriberResponse.getResponseMessage(), "Test Message");
291         assertThat(dmaapMRSubscriberResponse.getFetchedMessages().size(), is(0));
292
293     }
294
295 }
296
297
298
299
300