cccfe0c762555321462bc4d76aca0ababa33b22b
[so.git] / bpmn / so-bpmn-infrastructure-common / src / test / java / org / onap / so / bpmn / infrastructure / pnf / dmaap / PnfEventReadyDmaapClientTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2018 Nokia.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.pnf.dmaap;
24
25
26 import static org.junit.Assert.assertEquals;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.verifyZeroInteractions;
32 import static org.mockito.Mockito.when;
33 import java.io.ByteArrayInputStream;
34 import java.io.IOException;
35 import java.lang.reflect.Field;
36 import java.util.Map;
37 import java.util.concurrent.ConcurrentHashMap;
38 import java.util.concurrent.ScheduledThreadPoolExecutor;
39 import org.apache.http.HttpEntity;
40 import org.apache.http.HttpResponse;
41 import org.apache.http.ProtocolVersion;
42 import org.apache.http.client.HttpClient;
43 import org.apache.http.client.methods.HttpGet;
44 import org.apache.http.entity.InputStreamEntity;
45 import org.apache.http.message.BasicHttpResponse;
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 import org.mockito.ArgumentCaptor;
50 import org.mockito.Mock;
51 import org.mockito.junit.MockitoJUnitRunner;
52 import org.onap.so.bpmn.infrastructure.pnf.dmaap.PnfEventReadyDmaapClient.DmaapTopicListenerThread;
53 import org.springframework.core.env.Environment;
54
55 @RunWith(MockitoJUnitRunner.class)
56 public class PnfEventReadyDmaapClientTest {
57
58     private static final String PNF_CORRELATION_ID = "corrTestId";
59     private static final String PNF_CORRELATION_ID_NOT_FOUND_IN_MAP = "otherCorrId";
60     private static final String JSON_EXAMPLE_WITH_PNF_CORRELATION_ID = "[{\"correlationId\": \"%s\","
61             + "\"value\":\"value1\"},{\"correlationId\": \"corr\",\"value\":\"value2\"}]";
62
63     private static final String JSON_EXAMPLE_WITH_NO_PNF_CORRELATION_ID = "[{\"key1\":\"value1\"}]";
64
65     private static final String HOST = "hostTest";
66     private static final int PORT = 1234;
67     private static final String PROTOCOL = "http";
68     private static final String URI_PATH_PREFIX = "eventsForTesting";
69     private static final String EVENT_TOPIC_TEST = "eventTopicTest";
70     private static final String CONSUMER_ID = "consumerTestId";
71     private static final String CONSUMER_GROUP = "consumerGroupTest";
72     private static final int TOPIC_LISTENER_DELAY_IN_SECONDS = 5;
73
74     @Mock
75     private Environment env;
76     private PnfEventReadyDmaapClient testedObject;
77
78     private DmaapTopicListenerThread testedObjectInnerClassThread;
79     private HttpClient httpClientMock;
80     private Runnable threadMockToNotifyCamundaFlow;
81     private ScheduledThreadPoolExecutor executorMock;
82
83     @Before
84     public void init() throws NoSuchFieldException, IllegalAccessException {
85         when(env.getProperty(eq("pnf.dmaap.port"), eq(Integer.class))).thenReturn(PORT);
86         when(env.getProperty(eq("pnf.dmaap.host"))).thenReturn(HOST);
87         when(env.getProperty(eq("pnf.dmaap.protocol"))).thenReturn(PROTOCOL);
88         when(env.getProperty(eq("pnf.dmaap.uriPathPrefix"))).thenReturn(URI_PATH_PREFIX);
89         when(env.getProperty(eq("pnf.dmaap.topicName"))).thenReturn(EVENT_TOPIC_TEST);
90         when(env.getProperty(eq("pnf.dmaap.consumerId"))).thenReturn(CONSUMER_ID);
91         when(env.getProperty(eq("pnf.dmaap.consumerGroup"))).thenReturn(CONSUMER_GROUP);
92         when(env.getProperty(eq("pnf.dmaap.topicListenerDelayInSeconds"), eq(Integer.class)))
93                 .thenReturn(TOPIC_LISTENER_DELAY_IN_SECONDS);
94         testedObject = new PnfEventReadyDmaapClient(env);
95         testedObjectInnerClassThread = testedObject.new DmaapTopicListenerThread();
96         httpClientMock = mock(HttpClient.class);
97         threadMockToNotifyCamundaFlow = mock(Runnable.class);
98         executorMock = mock(ScheduledThreadPoolExecutor.class);
99         setPrivateField();
100     }
101
102     /**
103      * Test run method, where the are following conditions:
104      * <p>
105      * - DmaapThreadListener is running, flag is set to true
106      * <p>
107      * - map is filled with one entry with the key that we get from response
108      * <p>
109      * run method should invoke thread from map to notify camunda process, remove element from the map (map is empty)
110      * and shutdown the executor because of empty map
111      */
112     @Test
113     public void pnfCorrelationIdIsFoundInHttpResponse_notifyAboutPnfReady() throws IOException {
114         when(httpClientMock.execute(any(HttpGet.class)))
115                 .thenReturn(createResponse(String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID)));
116         testedObjectInnerClassThread.run();
117         ArgumentCaptor<HttpGet> captor1 = ArgumentCaptor.forClass(HttpGet.class);
118         verify(httpClientMock).execute(captor1.capture());
119
120         assertEquals(captor1.getValue().getURI().getHost(), HOST);
121         assertEquals(captor1.getValue().getURI().getPort(), PORT);
122         assertEquals(captor1.getValue().getURI().getScheme(), PROTOCOL);
123         assertEquals(captor1.getValue().getURI().getPath(),
124                 "/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + "");
125
126         verify(threadMockToNotifyCamundaFlow).run();
127         verify(executorMock).shutdown();
128     }
129
130     /**
131      * Test run method, where the are following conditions:
132      * <p>
133      * - DmaapThreadListener is running, flag is set to true
134      * <p>
135      * - map is filled with one entry with the pnfCorrelationId that does not match to pnfCorrelationId taken from http
136      * response. run method should not do anything with the map not run any thread to notify camunda process
137      */
138     @Test
139     public void pnfCorrelationIdIsFoundInHttpResponse_NotFoundInMap() throws IOException {
140         when(httpClientMock.execute(any(HttpGet.class))).thenReturn(createResponse(
141                 String.format(JSON_EXAMPLE_WITH_PNF_CORRELATION_ID, PNF_CORRELATION_ID_NOT_FOUND_IN_MAP)));
142         testedObjectInnerClassThread.run();
143         verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
144     }
145
146     /**
147      * Test run method, where the are following conditions:
148      * <p>
149      * - DmaapThreadListener is running, flag is set to true
150      * <p>
151      * - map is filled with one entry with the pnfCorrelationId but no correlation id is taken from HttpResponse run
152      * method should not do anything with the map and not run any thread to notify camunda process
153      */
154     @Test
155     public void pnfCorrelationIdIsNotFoundInHttpResponse() throws IOException {
156         when(httpClientMock.execute(any(HttpGet.class)))
157                 .thenReturn(createResponse(JSON_EXAMPLE_WITH_NO_PNF_CORRELATION_ID));
158         testedObjectInnerClassThread.run();
159         verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
160     }
161
162     private void setPrivateField() throws NoSuchFieldException, IllegalAccessException {
163         Field httpClientField = testedObject.getClass().getDeclaredField("httpClient");
164         httpClientField.setAccessible(true);
165         httpClientField.set(testedObject, httpClientMock);
166         httpClientField.setAccessible(false);
167
168         Field executorField = testedObject.getClass().getDeclaredField("executor");
169         executorField.setAccessible(true);
170         executorField.set(testedObject, executorMock);
171         executorField.setAccessible(false);
172
173         Field pnfCorrelationToThreadMapField = testedObject.getClass().getDeclaredField("pnfCorrelationIdToThreadMap");
174         pnfCorrelationToThreadMapField.setAccessible(true);
175         Map<String, Runnable> pnfCorrelationToThreadMap = new ConcurrentHashMap<>();
176         pnfCorrelationToThreadMap.put(PNF_CORRELATION_ID, threadMockToNotifyCamundaFlow);
177         pnfCorrelationToThreadMapField.set(testedObject, pnfCorrelationToThreadMap);
178
179         Field threadRunFlag = testedObject.getClass().getDeclaredField("dmaapThreadListenerIsRunning");
180         threadRunFlag.setAccessible(true);
181         threadRunFlag.set(testedObject, true);
182         threadRunFlag.setAccessible(false);
183     }
184
185     private HttpResponse createResponse(String json) {
186         HttpEntity entity = new InputStreamEntity(new ByteArrayInputStream(json.getBytes()));
187         ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
188         HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
189         response.setEntity(entity);
190         response.setStatusCode(200);
191         return response;
192     }
193
194 }