Change code in appc dispatcher for new LCMs in R6
[appc.git] / appc-sdc-listener / appc-sdc-listener-bundle / src / test / java / org / onap / appc / sdc / listener / SdcCallbackTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
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.appc.sdc.listener;
24
25
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 import org.mockito.Matchers;
31 import org.mockito.Mockito;
32 import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService;
33 import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator;
34 import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory;
35 import org.onap.appc.sdc.artifacts.impl.ToscaCsarArtifactProcessor;
36 import org.onap.appc.sdc.artifacts.object.SDCArtifact;
37 import org.onap.appc.sdc.artifacts.object.SDCReference;
38 import org.onap.appc.srvcomm.messaging.event.EventSender;
39 import org.onap.sdc.api.IDistributionClient;
40 import org.onap.sdc.api.consumer.INotificationCallback;
41 import org.onap.sdc.api.notification.IArtifactInfo;
42 import org.onap.sdc.api.notification.INotificationData;
43 import org.onap.sdc.api.notification.IResourceInstance;
44 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
45 import org.onap.sdc.impl.DistributionClientDownloadResultImpl;
46 import org.onap.sdc.utils.DistributionActionResultEnum;
47 import org.powermock.api.mockito.PowerMockito;
48 import org.powermock.core.classloader.annotations.PrepareForTest;
49 import org.powermock.modules.junit4.PowerMockRunner;
50 import org.powermock.reflect.Whitebox;
51
52 import java.io.File;
53 import java.io.FileInputStream;
54 import java.io.IOException;
55 import java.lang.reflect.Constructor;
56 import java.lang.reflect.InvocationTargetException;
57 import java.lang.reflect.Method;
58 import java.net.URISyntaxException;
59 import java.util.ArrayList;
60 import java.util.Arrays;
61 import java.util.List;
62 import java.util.stream.Collectors;
63
64 import static org.mockito.Matchers.anyObject;
65 import static org.mockito.Matchers.anyString;
66
67 @RunWith(PowerMockRunner.class)
68 @PrepareForTest({IDistributionClient.class,
69         EventSender.class,
70         ArtifactStorageService.class,
71         ToscaCsarArtifactProcessor.class,
72         ArtifactProcessorFactory.class,
73         DependencyModelGenerator.class})
74 public class SdcCallbackTest {
75
76     private INotificationCallback sdcCallback;
77     private ArtifactStorageService storageService;
78     private ToscaCsarArtifactProcessor artifactProcessor;
79     private String resourceContent;
80
81
82     @Before
83     public void setup() throws Exception {
84         IDistributionClient client = PowerMockito.mock(IDistributionClient.class);
85         EventSender eventSender = PowerMockito.mock(EventSender.class);
86         sdcCallback = new SdcCallback(null, client);
87         resourceContent =
88                 readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(), "");
89         artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(
90                 client, eventSender, getNotificationData(), getResources().get(0), getServiceArtifacts().get(0), null));
91         storageService = PowerMockito.mock(ArtifactStorageService.class);
92         Whitebox.setInternalState(artifactProcessor, "artifactStorageService", storageService);
93         DependencyModelGenerator dependencyModelGeneratorMock = PowerMockito.mock(DependencyModelGenerator.class);
94         PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(anyString(), anyString()))
95                 .thenReturn("Dependency_model");
96         Whitebox.setInternalState(artifactProcessor, "dependencyModelGenerator", dependencyModelGeneratorMock);
97
98         PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact(anyObject());
99         PowerMockito.doCallRealMethod().when(artifactProcessor).run();
100
101         //PowerMockito.mockStatic(ArtifactProcessorFactory.class);
102         ArtifactProcessorFactory artifactProcessorFactory = PowerMockito.mock(ArtifactProcessorFactory.class);
103         PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(
104                 /* (IDistributionClient) */ anyObject(), /* (EventSender) */ anyObject(),
105                 /* (INotificationData) */ anyObject(), /* (IResourceInstance) */ anyObject(),
106                 /* (IArtifactInfo) */ anyObject(), /* (URI) */ anyObject()))
107                 .thenReturn(artifactProcessor);
108
109         Whitebox.setInternalState(sdcCallback, "eventSender", eventSender);
110         PowerMockito.doReturn(readDownloadResult()).when(client).download(/* (IArtifactInfo) */ anyObject());
111         PowerMockito.doReturn(null).when(client).sendDownloadStatus(/* (IDistributionStatusMessage) */ anyObject());
112
113         PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(anyString(), anyString(), anyString());
114
115         PowerMockito.doAnswer(invocationOnMock -> {
116             System.out.print(invocationOnMock.getArguments()[0].toString());
117             return null;
118         }).when(storageService).storeSDCArtifact(/* (SDCArtifact) */ anyObject());
119     }
120
121     private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException {
122         DistributionClientDownloadResultImpl downloadResult =
123                 new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "Download success");
124         File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI());
125
126         byte[] bFile = new byte[(int) file.length()];
127         try (FileInputStream fileInputStream = new FileInputStream(file)) {
128             fileInputStream.read(bFile);
129         } catch (Exception e){
130             e.printStackTrace();
131         }
132
133         downloadResult.setArtifactPayload(bFile);
134         return downloadResult;
135     }
136
137
138     @Test
139     public void testSDCListener()
140             throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
141         INotificationData notificationData = getNotificationData();
142         sdcCallback.activateCallback(notificationData);
143         pause();
144     }
145
146     @Test
147     public void testArtifacts() throws Exception {
148         PowerMockito.doAnswer(invocationOnMock -> {
149             SDCArtifact artifact = (SDCArtifact) invocationOnMock.getArguments()[0];
150             SDCReference reference = (SDCReference) invocationOnMock.getArguments()[1];
151             Assert.assertEquals("abcd-efgh-ijkl", artifact.getArtifactUUID());
152             Assert.assertEquals("Resource-APPC", reference.getVnfType());
153             Assert.assertEquals(resourceContent.trim(),
154                     artifact.getArtifactContent().replaceAll(System.lineSeparator(), ""));
155             return null;
156         }).doAnswer(invocation -> {
157             SDCArtifact artifact = (SDCArtifact) invocation.getArguments()[0];
158             SDCReference reference = (SDCReference) invocation.getArguments()[1];
159             Assert.assertEquals("Resource-APPC", reference.getVnfType());
160             Assert.assertEquals("tosca_dependency_model", reference.getFileCategory());
161             Assert.assertEquals("Dependency_model", artifact.getArtifactContent());
162             Assert.assertEquals("Resource-APPC", artifact.getResourceName());
163             return null;
164         }).when(storageService).storeSDCArtifactWithReference(anyObject(), anyObject());
165
166         artifactProcessor.processArtifact(readDownloadResult());
167     }
168
169     private void pause(){
170         try {
171             Thread.sleep(5000);
172         } catch (InterruptedException e) {
173         }
174     }
175
176     private String readInput(String inputFile) throws URISyntaxException {
177         File file = new File(this.getClass().getResource(inputFile).toURI());
178         byte[] bFile = new byte[(int) file.length()];
179         try (FileInputStream fileInputStream = new FileInputStream(file)) {
180             fileInputStream.read(bFile);
181         } catch (Exception e){
182             e.printStackTrace();
183         }
184         return new String(bFile);
185     }
186
187     private INotificationData getNotificationData()
188             throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
189
190         INotificationData notificationData =
191                 (INotificationData) getObject("org.onap.sdc.impl.NotificationDataImpl");
192
193         List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
194
195         invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts);
196         return notificationData;
197     }
198
199     private List<IResourceInstance> getResources()
200             throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
201         List<IResourceInstance> resources = new ArrayList<>();
202         IResourceInstance resource =
203                 (IResourceInstance) getObject("org.onap.sdc.impl.JsonContainerResourceInstance");
204
205         List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
206         invokeMethod(resource, "setArtifacts", serviceArtifacts);
207         invokeMethod(resource, "setResourceName", "Vnf");
208         invokeMethod(resource, "setResourceVersion", "1.0");
209
210         resources.add(resource);
211         return resources;
212     }
213
214     private void invokeMethod(Object object, String methodName, Object... arguments)
215             throws IllegalAccessException, InvocationTargetException {
216         Method[] methods = object.getClass().getDeclaredMethods();
217         for(Method method : methods) {
218             if(methodName.equalsIgnoreCase(method.getName())){
219                 method.setAccessible(true);
220                 method.invoke(object, arguments);
221             }
222         }
223     }
224
225     private Object getObject(String fqcn)
226             throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
227         Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors())
228                 .stream()
229                 .filter(constructor1 -> constructor1.getParameterCount() == 0)
230                 .collect(Collectors.toList())
231                 .get(0);
232         constructor.setAccessible(true);
233         return constructor.newInstance();
234     }
235
236     private List<IArtifactInfo> getServiceArtifacts()
237             throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
238         List<IArtifactInfo> serviceArtifacts = new ArrayList<>();
239         IArtifactInfo artifactInfo = (IArtifactInfo) getObject("org.onap.sdc.impl.ArtifactInfoImpl");
240         invokeMethod(artifactInfo, "setArtifactType", "TOSCA_CSAR");
241         invokeMethod(artifactInfo, "setArtifactUUID", "abcd-efgh-ijkl");
242         serviceArtifacts.add(artifactInfo);
243         return serviceArtifacts;
244     }
245 }