Fix for test coverage in oam.utils package
[appc.git] / appc-oam / appc-oam-bundle / src / test / java / org / onap / appc / oam / util / BundleHelperTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications (C) 2018 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  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.oam.util;
27
28 import static org.hamcrest.CoreMatchers.isA;
29
30 import com.att.eelf.configuration.EELFLogger;
31 import com.google.common.collect.ImmutableMap;
32 import org.apache.commons.lang.ArrayUtils;
33 import org.junit.Assert;
34 import org.junit.Before;
35 import org.junit.Rule;
36 import org.junit.Test;
37 import org.junit.rules.ExpectedException;
38 import org.junit.runner.RunWith;
39 import org.mockito.Mockito;
40 import org.onap.appc.configuration.Configuration;
41 import org.onap.appc.exceptions.APPCException;
42 import org.onap.appc.oam.AppcOam;
43 import org.onap.appc.oam.processor.BaseCommon;
44 import org.onap.appc.oam.util.BundleHelper.BundleTask;
45 import org.onap.appc.statemachine.impl.readers.AppcOamStates;
46 import org.osgi.framework.Bundle;
47 import org.osgi.framework.BundleContext;
48 import org.osgi.framework.FrameworkUtil;
49 import org.powermock.api.mockito.PowerMockito;
50 import org.powermock.api.support.membermodification.MemberMatcher;
51 import org.powermock.core.classloader.annotations.PrepareForTest;
52 import org.powermock.modules.junit4.PowerMockRunner;
53 import org.powermock.reflect.Whitebox;
54
55 import java.util.Arrays;
56 import java.util.HashMap;
57 import java.util.List;
58 import java.util.Map;
59 import java.util.concurrent.Callable;
60 import java.util.concurrent.ExecutionException;
61 import java.util.concurrent.Future;
62 import java.util.concurrent.FutureTask;
63 import static org.junit.Assert.assertEquals;
64 import static org.junit.Assert.assertFalse;
65 import static org.junit.Assert.assertTrue;
66 import static org.mockito.Matchers.any;
67 import static org.mockito.Mockito.mock;
68 import static org.mockito.Mockito.times;
69 import static org.powermock.api.mockito.PowerMockito.mockStatic;
70 import static org.powermock.api.mockito.PowerMockito.spy;
71
72 @RunWith(PowerMockRunner.class)
73 @PrepareForTest(FrameworkUtil.class)
74 public class BundleHelperTest {
75     private BundleHelper bundleHelper;
76     private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class);
77
78     @Rule
79     public ExpectedException expectedEx = ExpectedException.none();
80
81     @Before
82     public void setUp() throws Exception {
83         bundleHelper = spy(new BundleHelper(null, null, null));
84
85         // to avoid operation on logger fail, mock up the logger
86         EELFLogger mockLogger = mock(EELFLogger.class);
87         Whitebox.setInternalState(bundleHelper, "logger", mockLogger);
88     }
89
90     @Test
91     public void testBundleOperations() throws Exception {
92         // spy mocked bundle for calls to method start or stop.
93         // Note: the time of method calls are accumulated in this test method.
94         Bundle mockBundle = spy(Mockito.mock(Bundle.class));
95         Map<String, Bundle> mapFromGetAppcLcmBundles = new HashMap<>();
96         mapFromGetAppcLcmBundles.put("BundleString", mockBundle);
97
98         PowerMockito.doReturn(mapFromGetAppcLcmBundles).when(bundleHelper, MemberMatcher.method(
99             BundleHelper.class, "getAppcLcmBundles")).withNoArguments();
100
101         StateHelper mockStateHelper = mock(StateHelper.class);
102         Whitebox.setInternalState(bundleHelper, "stateHelper", mockStateHelper);
103
104         AppcOamStates appcOamStates = AppcOamStates.Stopped;
105         Mockito.doReturn(appcOamStates).when(mockStateHelper).getState();
106
107         // test start
108         Mockito.doReturn(true).when(mockStateHelper).isSameState(appcOamStates);
109         boolean result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null);
110         Assert.assertTrue("Should be completed", result);
111         Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any());
112
113         // test start aborted
114         Mockito.doReturn(false).when(mockStateHelper).isSameState(appcOamStates);
115         result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null);
116         Assert.assertFalse("Should be abort", result);
117         Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any());
118
119         // test stop
120         result = bundleHelper.bundleOperations(AppcOam.RPC.stop, new HashMap<>(), mockTaskHelper,null);
121         Assert.assertTrue("Should be completed", result);
122         Mockito.verify(mockTaskHelper, times(2)).submitBaseSubCallable(any());
123     }
124
125     @Test(expected = APPCException.class)
126     public void testBundleOperationsRpcException() throws Exception {
127         bundleHelper.bundleOperations(AppcOam.RPC.maintenance_mode, new HashMap<>(), mockTaskHelper,null);
128     }
129
130     @Test
131     public void testGetBundleList() throws Exception {
132         mockStatic(FrameworkUtil.class);
133         Bundle myBundle = mock(Bundle.class);
134         PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle);
135
136         // test bundle context is null
137         Mockito.when(myBundle.getBundleContext()).thenReturn(null);
138         Assert.assertTrue("Should return null", bundleHelper.getBundleList() == null);
139
140         BundleContext myBundleContext = mock(BundleContext.class);
141         Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext);
142
143         // test bundle list is empty
144         Bundle[] bundleArray = {};
145         Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray);
146         Bundle[] results = bundleHelper.getBundleList();
147         Assert.assertTrue("Should not be null", results != null);
148         Assert.assertTrue("Should not have any element", results.length == 0);
149
150         // test bundle list has at one bundle
151         bundleArray = new Bundle[] { myBundle };
152         Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray);
153         results = bundleHelper.getBundleList();
154         Assert.assertTrue("Should not be null", results != null);
155         Assert.assertTrue("Should have one element", results.length == 1);
156         Assert.assertEquals("Should be the mock bundle", myBundle, results[0]);
157     }
158
159     @Test
160     public void testReadPropsFromPropListName() throws Exception {
161         // mock configuarion helper
162         ConfigurationHelper configurationHelper = new ConfigurationHelper(null);
163         EELFLogger fakeLogger = mock(EELFLogger.class);
164         Whitebox.setInternalState(configurationHelper, "logger", fakeLogger);
165         Configuration fakeConf = mock(Configuration.class);
166         Whitebox.setInternalState(configurationHelper, "configuration", fakeConf);
167
168         Whitebox.setInternalState(bundleHelper, "configurationHelper", configurationHelper);
169
170         String propKey = "testing";
171         // Property does not exist
172         Mockito.doReturn(null).when(fakeConf).getProperty(propKey);
173         String[] propResult = bundleHelper.readPropsFromPropListName(propKey);
174         Assert.assertArrayEquals("PropertyResult should be empty string array",
175             ArrayUtils.EMPTY_STRING_ARRAY, propResult);
176         // Property has one entry
177         String propValue1 = "1234";
178         String propValue2 = "5678";
179         Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey);
180         Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1);
181         propResult = bundleHelper.readPropsFromPropListName(propKey);
182         Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1);
183         Assert.assertEquals("PropertyResult should martch propertyValue", propValue2, propResult[0]);
184         // Property has two entries
185         propValue1 = "1234\n,4321";
186         String propValue3 = "8765";
187         Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey);
188         Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1);
189         Mockito.doReturn(propValue3).when(fakeConf).getProperty("4321");
190         propResult = bundleHelper.readPropsFromPropListName(propKey);
191         Assert.assertTrue("PropertyResult should have two elements", propResult.length == 2);
192         List<String> propResultList = Arrays.asList(propResult);
193         Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue2));
194         Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue3));
195     }
196
197     @Test
198     public void testIsTaskAllDone() throws InterruptedException, ExecutionException {
199         assertTrue(bundleHelper.isAllTaskDone(getMapForTests(true)));
200     }
201
202     @Test
203     public void testIsTaskAllDoneNotDone() throws InterruptedException, ExecutionException {
204         assertFalse(bundleHelper.isAllTaskDone(getMapForTests(false)));
205     }
206
207     @Test
208     public void testCancelUnfinished() throws InterruptedException, ExecutionException {
209         Map<String, Future<?>> map = getMapForTests(false);
210         bundleHelper.cancelUnfinished(map);
211         Mockito.verify(map.get("TEST_KEY"), Mockito.times(1)).cancel(true);
212     }
213
214     @Test
215     public void testGetFailedMetrics() throws InterruptedException, ExecutionException {
216         Map<String, Future<?>> map = getMapForTests(false);
217         FutureTask<String> mockFutureTask = (FutureTask<String>) map.get("TEST_KEY"); 
218         Mockito.doReturn(Mockito.mock(BundleHelper.BundleTask.class)).when(mockFutureTask).get();
219         assertEquals(0, bundleHelper.getFailedMetrics(map));
220     }
221
222     @Test
223     public void testGetFailedMetricsExceptionFlow() throws InterruptedException, ExecutionException {
224         Map<String, Future<?>> map = getMapForTests(false);
225         FutureTask<String> mockFutureTask = (FutureTask<String>) map.get("TEST_KEY"); 
226         Mockito.doThrow(new ExecutionException("TestExecutionException", new Throwable())).when(mockFutureTask).get();
227         expectedEx.expect(RuntimeException.class);
228         expectedEx.expectCause(isA(ExecutionException.class));
229         bundleHelper.getFailedMetrics(map);
230     }
231
232     @Test
233     public void testGetAppcLcmBundles() {
234         Mockito.doReturn(null).when(bundleHelper).readPropsFromPropListName(Mockito.anyString());
235         mockStatic(FrameworkUtil.class);
236         Bundle myBundle = mock(Bundle.class);
237         PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle);
238         BundleFilter mockBundleFilter = Mockito.mock(BundleFilter.class);
239         Mockito.doReturn(mockBundleFilter).when(bundleHelper).getBundleFilter(null, null, null);
240         assertTrue(bundleHelper.getAppcLcmBundles().isEmpty());
241     }
242
243     @Test
244     public void testBundleTask() throws Exception {
245         AppcOam.RPC mockRpc = AppcOam.RPC.maintenance_mode;
246         Bundle mockBundle = Mockito.mock(Bundle.class);
247         BaseCommon mockBaseCommon = Mockito.mock(BaseCommon.class);
248         assertTrue(bundleHelper. new BundleTask(mockRpc, mockBundle, mockBaseCommon) instanceof BundleHelper.BundleTask);
249     }
250
251     private Map<String, Future<?>> getMapForTests(boolean isDone) throws InterruptedException, ExecutionException {
252         Callable<String> callable = new Callable<String>() {
253             @Override
254             public String call() throws Exception {
255                 return "CALLED";
256             }
257         };
258         FutureTask<String> futureTask = Mockito.spy(new FutureTask<String>(callable));
259         Mockito.doReturn(isDone).when(futureTask).isDone();
260         Map<String, Future<?>> map = ImmutableMap.of("TEST_KEY", futureTask);
261         return map;
262     }
263 }