Merge "path corrections in the cockpit"
[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  * 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.so.bpmn.infrastructure.pnf.dmaap;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.mockito.Matchers.any;
25 import static org.mockito.Matchers.eq;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.verify;
28 import static org.mockito.Mockito.verifyZeroInteractions;
29 import static org.mockito.Mockito.when;
30
31 import java.io.IOException;
32 import java.io.UnsupportedEncodingException;
33 import java.lang.reflect.Field;
34 import java.util.Map;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.ScheduledExecutorService;
37
38 import org.apache.http.HttpEntity;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.ProtocolVersion;
41 import org.apache.http.client.HttpClient;
42 import org.apache.http.client.methods.HttpGet;
43 import org.apache.http.entity.StringEntity;
44 import org.apache.http.message.BasicHttpResponse;
45 import org.junit.Before;
46 import org.junit.Test;
47 import org.junit.runner.RunWith;
48 import org.mockito.ArgumentCaptor;
49 import org.mockito.InjectMocks;
50 import org.mockito.Mock;
51 import org.mockito.runners.MockitoJUnitRunner;
52 import org.onap.so.bpmn.infrastructure.pnf.dmaap.PnfEventReadyDmaapClient.DmaapTopicListenerThread;
53 import org.springframework.core.env.Environment;
54 @RunWith(MockitoJUnitRunner.class)
55 public class PnfEventReadyDmaapClientTest {
56
57     private static final String CORRELATION_ID = "corrTestId";
58     private static final String CORRELATION_ID_NOT_FOUND_IN_MAP = "otherCorrId";
59     private static final String JSON_EXAMPLE_WITH_CORRELATION_ID = "[\n"
60             + "    {\n"
61             + "        \"pnfRegistrationFields\" : {\n"
62             + "        \"correlationId\" : \"%s\",\n"
63             + "        \"value\" : \"value1\"\n"
64             + "        }\n"
65             + "    },\n"
66             + "    {\n"
67             + "        \"pnfRegistrationFields\" : {\n"
68             + "        \"correlationId\" : \"corr\",\n"
69             + "        \"value\" : \"value2\"\n"
70             + "        }\n"
71             + "    }\n"
72             + "]";
73     private static final String JSON_EXAMPLE_WITH_NO_CORRELATION_ID =
74             "{\"pnfRegistrationFields\":{\"field\":\"value\"}}";
75
76     private static final String HOST = "hostTest";
77     private static final int PORT = 1234;
78     private static final String PROTOCOL = "http";
79     private static final String URI_PATH_PREFIX = "eventsForTesting";
80     private static final String EVENT_TOPIC_TEST = "eventTopicTest";
81     private static final String CONSUMER_ID = "consumerTestId";
82     private static final String CONSUMER_GROUP = "consumerGroupTest";
83     @Mock
84     private Environment env;
85     @InjectMocks
86     private PnfEventReadyDmaapClient testedObject = new PnfEventReadyDmaapClient();
87 ;
88     private DmaapTopicListenerThread testedObjectInnerClassThread;
89     private HttpClient httpClientMock;
90     private Runnable threadMockToNotifyCamundaFlow;
91     private ScheduledExecutorService executorMock;
92
93     @Before
94     public void init() throws NoSuchFieldException, IllegalAccessException {
95         when(env.getProperty(eq("pnf.dmaap.port"), eq(Integer.class))).thenReturn(PORT);
96         when(env.getProperty(eq("pnf.dmaap.host"))).thenReturn(HOST);
97         testedObject.setDmaapProtocol(PROTOCOL);
98         testedObject.setDmaapUriPathPrefix(URI_PATH_PREFIX);
99         testedObject.setDmaapTopicName(EVENT_TOPIC_TEST);
100         testedObject.setConsumerId(CONSUMER_ID);
101         testedObject.setConsumerGroup(CONSUMER_GROUP);
102         testedObject.setDmaapClientDelayInSeconds(1);
103         testedObject.init();
104         testedObjectInnerClassThread = testedObject.new DmaapTopicListenerThread();
105         httpClientMock = mock(HttpClient.class);
106         threadMockToNotifyCamundaFlow = mock(Runnable.class);
107         executorMock = mock(ScheduledExecutorService.class);
108         setPrivateField();
109     }
110
111     /**
112      * Test run method, where the are following conditions:
113      * <p> - DmaapThreadListener is running, flag is set to true
114      * <p> - map is filled with one entry with the key that we get from response
115      * <p> run method should invoke thread from map to notify camunda process, remove element from the map (map is
116      * empty) and shutdown the executor because of empty map
117      */
118     @Test
119     public void correlationIdIsFoundInHttpResponse_notifyAboutPnfReady()
120             throws IOException {
121         when(httpClientMock.execute(any(HttpGet.class))).
122                 thenReturn(createResponse(String.format(JSON_EXAMPLE_WITH_CORRELATION_ID, CORRELATION_ID)));
123         testedObjectInnerClassThread.run();
124         ArgumentCaptor<HttpGet> captor1 = ArgumentCaptor.forClass(HttpGet.class);
125         verify(httpClientMock).execute(captor1.capture());
126         assertThat(captor1.getValue().getURI()).hasHost(HOST).hasPort(PORT).hasScheme(PROTOCOL)
127                 .hasPath(
128                         "/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + "");
129         verify(threadMockToNotifyCamundaFlow).run();
130         verify(executorMock).shutdownNow();
131     }
132
133     /**
134      * Test run method, where the are following conditions:
135      * <p> - DmaapThreadListener is running, flag is set to true
136      * <p> - map is filled with one entry with the correlationId that does not match to correlationId
137      * taken from http response. run method should not do anything with the map not run any thread to notify camunda
138      * process
139      */
140     @Test
141     public void correlationIdIsFoundInHttpResponse_NotFoundInMap()
142             throws IOException {
143         when(httpClientMock.execute(any(HttpGet.class))).
144                 thenReturn(createResponse(
145                         String.format(JSON_EXAMPLE_WITH_CORRELATION_ID, CORRELATION_ID_NOT_FOUND_IN_MAP)));
146         testedObjectInnerClassThread.run();
147         verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
148     }
149
150     /**
151      * Test run method, where the are following conditions:
152      * <p> - DmaapThreadListener is running, flag is set to true
153      * <p> - map is filled with one entry with the correlationId but no correlation id is taken from HttpResponse
154      * run method should not do anything with the map and not run any thread to notify camunda process
155      */
156     @Test
157     public void correlationIdIsNotFoundInHttpResponse() throws IOException {
158         when(httpClientMock.execute(any(HttpGet.class))).
159                 thenReturn(createResponse(JSON_EXAMPLE_WITH_NO_CORRELATION_ID));
160         testedObjectInnerClassThread.run();
161         verifyZeroInteractions(threadMockToNotifyCamundaFlow, executorMock);
162     }
163
164     private void setPrivateField() throws NoSuchFieldException, IllegalAccessException {
165         Field httpClientField = testedObject.getClass().getDeclaredField("httpClient");
166         httpClientField.setAccessible(true);
167         httpClientField.set(testedObject, httpClientMock);
168         httpClientField.setAccessible(false);
169
170         Field executorField = testedObject.getClass().getDeclaredField("executor");
171         executorField.setAccessible(true);
172         executorField.set(testedObject, executorMock);
173         executorField.setAccessible(false);
174
175         Field pnfCorrelationToThreadMapField = testedObject.getClass()
176                 .getDeclaredField("pnfCorrelationIdToThreadMap");
177         pnfCorrelationToThreadMapField.setAccessible(true);
178         Map<String, Runnable> pnfCorrelationToThreadMap = new ConcurrentHashMap<>();
179         pnfCorrelationToThreadMap.put(CORRELATION_ID, threadMockToNotifyCamundaFlow);
180         pnfCorrelationToThreadMapField.set(testedObject, pnfCorrelationToThreadMap);
181
182         Field threadRunFlag = testedObject.getClass().getDeclaredField("dmaapThreadListenerIsRunning");
183         threadRunFlag.setAccessible(true);
184         threadRunFlag.set(testedObject, true);
185         threadRunFlag.setAccessible(false);
186     }
187
188     private HttpResponse createResponse(String json) throws UnsupportedEncodingException {
189         HttpEntity entity = new StringEntity(json);
190         ProtocolVersion protocolVersion = new ProtocolVersion("", 1, 1);
191         HttpResponse response = new BasicHttpResponse(protocolVersion, 1, "");
192         response.setEntity(entity);
193         response.setStatusCode(200);
194         return response;
195     }
196
197 }