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