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