Change sdc client version
[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-2018 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.adapter.message.EventSender;
33 import org.onap.appc.sdc.artifacts.helper.ArtifactStorageService;
34 import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator;
35 import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory;
36 import org.onap.appc.sdc.artifacts.impl.ToscaCsarArtifactProcessor;
37 import org.onap.appc.sdc.artifacts.object.SDCArtifact;
38 import org.onap.appc.sdc.artifacts.object.SDCReference;
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
66 @RunWith(PowerMockRunner.class)
67 @PrepareForTest({IDistributionClient.class,
68         EventSender.class,
69         ArtifactStorageService.class,
70         ToscaCsarArtifactProcessor.class,
71         ArtifactProcessorFactory.class,
72         DependencyModelGenerator.class})
73 public class SdcCallbackTest {
74
75     private INotificationCallback sdcCallback;
76     private ArtifactStorageService storageService;
77     private ToscaCsarArtifactProcessor artifactProcessor;
78     private String resourceContent;
79
80
81     @Before
82     public void setup() throws Exception {
83         IDistributionClient client = PowerMockito.mock(IDistributionClient.class);
84         EventSender eventSender = PowerMockito.mock(EventSender.class);
85         sdcCallback = new SdcCallback(null, client);
86         resourceContent=readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(),"");
87         artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client, eventSender, getNotificationData(), getResources().get(0)
88                 , getServiceArtifacts().get(0), null));
89         storageService = PowerMockito.mock(ArtifactStorageService.class);
90         Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService);
91         DependencyModelGenerator dependencyModelGeneratorMock=PowerMockito.mock(DependencyModelGenerator.class);
92         PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(Matchers.anyString(),Matchers.anyString()))
93                 .thenReturn("Dependency_model");
94         Whitebox.setInternalState(artifactProcessor,"dependencyModelGenerator",dependencyModelGeneratorMock);
95
96         PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact(anyObject());
97         PowerMockito.doCallRealMethod().when(artifactProcessor).run();
98
99         //PowerMockito.mockStatic(ArtifactProcessorFactory.class);
100         ArtifactProcessorFactory artifactProcessorFactory=PowerMockito.mock(ArtifactProcessorFactory.class);
101         PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(anyObject(), anyObject(),
102                 anyObject(), anyObject(),
103                 anyObject(), anyObject())).thenReturn(artifactProcessor);
104
105         Whitebox.setInternalState(sdcCallback,"eventSender", eventSender);
106         PowerMockito.doReturn(readDownloadResult()).when(client).download(anyObject());
107         PowerMockito.doReturn(null).when(client).sendDownloadStatus(anyObject());
108
109         PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(),
110                 Matchers.anyString(),Matchers.anyString());
111
112         PowerMockito.doAnswer(invocationOnMock -> {
113             System.out.print(invocationOnMock.getArguments()[0].toString());
114             return null;
115         }).when(storageService).storeSDCArtifact(anyObject());
116     }
117
118     private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException {
119         DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl
120                 (DistributionActionResultEnum.SUCCESS,"Download success");
121         File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI());
122
123         byte[] bFile = new byte[(int) file.length()];
124         FileInputStream fileInputStream = new FileInputStream(file);
125         fileInputStream.read(bFile);
126         fileInputStream.close();
127
128         downloadResult.setArtifactPayload(bFile);
129         return downloadResult;
130     }
131
132
133     @Test
134     public void testSDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
135         INotificationData notificationData = getNotificationData();
136         sdcCallback.activateCallback(notificationData);
137         pause();
138     }
139
140     @Test
141     public void testArtifacts() throws Exception {
142         PowerMockito.doAnswer(invocationOnMock -> {
143             SDCArtifact artifact =(SDCArtifact)invocationOnMock.getArguments()[0];
144             SDCReference reference=(SDCReference)invocationOnMock.getArguments()[1];
145             Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID());
146             Assert.assertEquals("Resource-APPC",reference.getVnfType());
147             Assert.assertEquals(resourceContent.trim(),artifact.getArtifactContent().replaceAll(System.lineSeparator(),""));
148             return null;
149         }).doAnswer(invocation -> {
150             SDCArtifact artifact =(SDCArtifact)invocation.getArguments()[0];
151             SDCReference reference=(SDCReference)invocation.getArguments()[1];
152             Assert.assertEquals("Resource-APPC",reference.getVnfType());
153             Assert.assertEquals("tosca_dependency_model",reference.getFileCategory());
154             Assert.assertEquals("Dependency_model",artifact.getArtifactContent());
155             Assert.assertEquals("Resource-APPC",artifact.getResourceName());
156             return null;
157         }).when(storageService).storeSDCArtifactWithReference(anyObject(),anyObject());
158
159         artifactProcessor.processArtifact(readDownloadResult());
160     }
161
162     private void pause(){
163         try {
164             Thread.sleep(5000);
165         } catch (InterruptedException e) {
166         }
167     }
168
169     private String readInput(String inputFile) throws URISyntaxException {
170         File file = new File(this.getClass().getResource(inputFile).toURI());
171         byte[] bFile = new byte[(int) file.length()];
172         try(FileInputStream fileInputStream = new FileInputStream(file)){
173             fileInputStream.read(bFile);
174         } catch (Exception e){
175             e.printStackTrace();
176         }
177         return new String(bFile);
178     }
179
180     private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
181
182         INotificationData notificationData = (INotificationData)getObject("org.onap.sdc.impl.NotificationDataImpl");
183
184         List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
185
186         invokeMethod(notificationData, "setServiceArtifacts", serviceArtifacts);
187         return notificationData;
188     }
189
190     private List<IResourceInstance> getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
191         List<IResourceInstance> resources = new ArrayList<>();
192         IResourceInstance resource = (IResourceInstance)getObject("org.onap.sdc.impl.JsonContainerResourceInstance");
193
194         List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
195         invokeMethod(resource,"setArtifacts",serviceArtifacts);
196         invokeMethod(resource,"setResourceName","Vnf");
197         invokeMethod(resource,"setResourceVersion","1.0");
198
199         resources.add(resource);
200         return resources;
201     }
202
203     private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException {
204         Method[] methods = object.getClass().getDeclaredMethods();
205         for(Method method:methods){
206             if(methodName.equalsIgnoreCase(method.getName())){
207                 method.setAccessible(true);
208                 method.invoke(object,arguments);
209             }
210         }
211     }
212
213     private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
214         Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors())
215                 .stream()
216                 .filter(constructor1 -> constructor1.getParameterCount()==0)
217                 .collect(Collectors.toList())
218                 .get(0);
219         constructor.setAccessible(true);
220         return constructor.newInstance();
221     }
222
223     private List<IArtifactInfo> getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
224         List<IArtifactInfo> serviceArtifacts = new ArrayList<>();
225         IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.onap.sdc.impl.ArtifactInfoImpl");
226         invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR");
227         invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl");
228         serviceArtifacts.add(artifactInfo);
229         return serviceArtifacts;
230     }
231 }