Dmaap micro service jar
[appc.git] / services / appc-dmaap-service / appc-event-listener-bundle / src / test / java / org / onap / appc / listener / impl / EventHandlerImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.listener.impl;
26
27 import static com.google.common.collect.Lists.newArrayList;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertFalse;
30 import static org.junit.Assert.assertNotNull;
31 import static org.junit.Assert.assertTrue;
32 import static org.mockito.Matchers.anyInt;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
35 import java.io.IOException;
36 import java.io.Serializable;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashSet;
40 import java.util.List;
41 import java.util.Properties;
42 import java.util.Set;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.junit.runner.RunWith;
46 import org.mockito.Mock;
47 import org.mockito.Mockito;
48 import org.mockito.runners.MockitoJUnitRunner;
49 import org.onap.appc.adapter.message.Consumer;
50 import org.onap.appc.adapter.message.Producer;
51 import org.onap.appc.listener.ListenerProperties;
52 import org.powermock.reflect.Whitebox;
53 import com.fasterxml.jackson.annotation.JsonProperty;
54 import com.fasterxml.jackson.databind.annotation.JsonSerialize;
55
56 /**
57  * Test the ProviderAdapter implementation.
58  */
59
60 @RunWith(MockitoJUnitRunner.class)
61 public class EventHandlerImplTest {
62
63     private TestEventHandlerImpl adapter;
64     private ListenerProperties properties;
65
66     @Mock
67     private Producer mockProducer;
68     @Mock
69     private Consumer mockConsumer;
70
71     private static final String PROP_FILE = "/org/onap/appc/default.properties";
72
73     private static final String MESSAGE_FILE = "/DCAEResponse.txt";
74
75     /**
76      * Setup the test environment.
77      */
78     @Before
79     public void setup() {
80         Properties allProps = new Properties();
81         try {
82             allProps.load(getClass().getResourceAsStream(PROP_FILE));
83             allProps.remove("appc.ClosedLoop.topic.read.filter");
84             properties = new ListenerProperties("appc.ClosedLoop", allProps);
85         } catch (IOException e) {
86             System.out.println("WARNING: Failed to load properties file: " + PROP_FILE);
87         }
88         adapter = new TestEventHandlerImpl(properties);
89         adapter.setConsumer(mockConsumer);
90         adapter.setProducer(mockProducer);
91     }
92
93     @Test
94     public void testInitialProperties() {
95         assertEquals(properties.getProperty("topic.read"), adapter.getReadTopic());
96         assertTrue(adapter.getWriteTopic().equals(properties.getProperty("topic.write")));
97         assertEquals(properties.getProperty("client.name"), adapter.getClientName());
98         assertEquals(properties.getProperty("client.name.id"), adapter.getClientId());
99
100         String hostStr = properties.getProperty("poolMembers");
101         int hostCount = hostStr.length() > 0 ? hostStr.split(",").length : 0;
102         assertEquals(hostCount, adapter.getPool().size());
103     }
104
105     @Test
106     public void testGettersAndSetters() {
107         String readTopic = "read";
108         String writeTopic = "write";
109         String clientName = "APPC-TEST";
110         String clientId = "00";
111         String newHost = "google.com";
112
113         adapter.setReadTopic(readTopic);
114         assertEquals(readTopic, adapter.getReadTopic());
115
116         adapter.setWriteTopic(writeTopic);
117         assertEquals(writeTopic, adapter.getWriteTopic());
118
119         adapter.setClientName(clientName);
120         assertEquals(clientName, adapter.getClientName());
121
122         adapter.setClientId(clientId);
123         assertEquals(clientId, adapter.getClientId());
124
125         adapter.setCredentials("fake", "secret");
126         adapter.clearCredentials();
127
128         int oldSize = adapter.getPool().size();
129         adapter.addToPool(newHost);
130         assertEquals(oldSize + 1, adapter.getPool().size());
131         assertTrue(adapter.getPool().contains(newHost));
132
133         adapter.removeFromPool(newHost);
134         assertEquals(oldSize, adapter.getPool().size());
135         assertFalse(adapter.getPool().contains(newHost));
136
137     }
138
139     @Test
140     public void getIncomingEvents_should_success_when_no_errors_encountered() {
141
142         List<String> testResult = newArrayList("test-result1", "test-result2", "test-result3");
143         when(mockConsumer.fetch(anyInt(), anyInt())).thenReturn(testResult);
144
145         List<String> result = adapter.getIncomingEvents(5);
146
147         for (int i = 0; i < testResult.size(); i++) {
148             assertEquals(testResult.get(i), result.get(i));
149         }
150     }
151
152
153     @Test
154     public void postStatus_should_success_when_no_errors_encountered() {
155
156         adapter.postStatus("test-partition", "test-event");
157         verify(mockProducer).post("test-partition", "test-event");
158
159         adapter.postStatus("test-event");
160         verify(mockProducer).post(null, "test-event");
161     }
162
163
164     @Test
165     public void closeClients_should_close_producer_and_consumer() {
166         adapter.getIncomingEvents(5);
167         adapter.postStatus("test-partition", "test-event");
168
169         adapter.closeClients();
170         verify(mockConsumer).close();
171         verify(mockProducer).close();
172     }
173
174     @Test
175     public void testGetEvents() {
176         EventHandlerImpl adapter = new EventHandlerImpl(properties);
177         Consumer consumer = Mockito.mock(Consumer.class);
178         Mockito.when(consumer.fetch(Mockito.anyInt(), Mockito.anyInt()))
179             .thenReturn(new ArrayList<String>(Arrays.asList("TEST1")));
180         Whitebox.setInternalState(adapter, "reader", consumer);
181         assertEquals("TEST1", adapter.getIncomingEvents().get(0));
182     }
183
184     @Test
185     public void testGetEventsClass() {
186         EventHandlerImpl adapter = new EventHandlerImpl(properties);
187         Consumer consumer = Mockito.mock(Consumer.class);
188         Mockito.when(consumer.fetch(Mockito.anyInt(), Mockito.anyInt()))
189             .thenReturn(new ArrayList<String>(Arrays.asList("1")));
190         Whitebox.setInternalState(adapter, "reader", consumer);
191         assertEquals(Integer.valueOf(1), adapter.getIncomingEvents(Integer.class).get(0));
192     }
193
194     @Test
195     public void testSetters() {
196         EventHandlerImpl adapter = new EventHandlerImpl(properties);
197         adapter.setResponseProblemBlacklistTime("1");
198         assertEquals("1", Whitebox.getInternalState(adapter, "responseProblemBlacklistTime"));
199         adapter.setServerProblemBlacklistTime("1");
200         assertEquals("1", Whitebox.getInternalState(adapter, "serverProblemBlacklistTime"));
201         adapter.setDnsIssueBlacklistTime("1");
202         assertEquals("1", Whitebox.getInternalState(adapter, "dnsIssueBlacklistTime"));
203         adapter.setIOExceptionBlacklistTime("1");
204         assertEquals("1", Whitebox.getInternalState(adapter, "ioExceptionBlacklistTime"));
205     }
206
207 //    @Test
208     public void testRun() {
209         EventHandlerImpl adapter = new EventHandlerImpl(properties);
210
211         // Runoff any old data
212         List<String> result = adapter.getIncomingEvents();
213         assertNotNull(result);
214
215         // Post new data
216         DummyObj data = new DummyObj();
217         data.key = "value";
218         adapter.postStatus(data.toJson());
219
220         // Wait to account for network delay
221         sleep(2000);
222
223         // Get data back
224         List<DummyObj> result2 = adapter.getIncomingEvents(DummyObj.class);
225         assertNotNull(result2);
226 //        assertEquals(1, result2.size());
227         assertEquals(data.toJson(), result2.get(0).toJson());
228     }
229
230     private class TestEventHandlerImpl extends EventHandlerImpl {
231
232         private Consumer mockConsumer;
233         private Producer mockProducer;
234
235         private TestEventHandlerImpl(ListenerProperties props) {
236             super(props);
237         }
238
239         @Override
240         protected Consumer getConsumer() {
241             return mockConsumer;
242         }
243
244         @Override
245         protected Producer getProducer() {
246             return mockProducer;
247         }
248
249         private void setConsumer(Consumer consumer) {
250             mockConsumer = consumer;
251         }
252
253         private void setProducer(Producer producer) {
254             mockProducer = producer;
255         }
256     }
257
258     @JsonSerialize
259     public static class DummyObj implements Serializable {
260
261         @JsonProperty("request") // Call request for default filter
262         public String key;
263
264         public DummyObj() {
265         }
266
267         public String toJson() {
268             return String.format("{\"request\": \"%s\"}", key);
269         }
270     }
271
272     private void sleep(long ms) {
273         try {
274             Thread.sleep(ms);
275         } catch (Exception e) {
276             return;
277         }
278     }
279 }