2d2c30865a011ae8fd1dbe08649d69e3dab78f71
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vendor-software-products-rest-services / src / test / java / org / openecomp / sdcrests / vsp / rest / services / OrchestrationTemplateCandidateImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdcrests.vsp.rest.services;
22
23 import static org.junit.jupiter.api.Assertions.assertEquals;
24 import static org.junit.jupiter.api.Assertions.assertFalse;
25 import static org.junit.jupiter.api.Assertions.assertNotEquals;
26 import static org.junit.jupiter.api.Assertions.assertNotNull;
27 import static org.junit.jupiter.api.Assertions.assertNull;
28 import static org.junit.jupiter.api.Assertions.assertTrue;
29 import static org.junit.jupiter.api.Assertions.fail;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.ArgumentMatchers.anyString;
32 import static org.mockito.Mockito.when;
33
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.net.URL;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.util.Arrays;
41 import java.util.Objects;
42 import java.util.Optional;
43 import java.util.UUID;
44 import javax.activation.DataHandler;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.Status;
47 import org.apache.commons.io.IOUtils;
48 import org.apache.commons.lang3.tuple.Pair;
49 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
50 import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
51 import org.junit.jupiter.api.BeforeEach;
52 import org.junit.jupiter.api.Test;
53 import org.mockito.ArgumentMatchers;
54 import org.mockito.InjectMocks;
55 import org.mockito.Mock;
56 import org.mockito.Mockito;
57 import org.mockito.MockitoAnnotations;
58 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
59 import org.openecomp.sdc.activitylog.ActivityLogManager;
60 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
61 import org.openecomp.sdc.be.csar.storage.MinIoArtifactInfo;
62 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig;
63 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig.Credentials;
64 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig.EndPoint;
65 import org.openecomp.sdc.be.csar.storage.PackageSizeReducer;
66 import org.openecomp.sdc.logging.api.Logger;
67 import org.openecomp.sdc.logging.api.LoggerFactory;
68 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
69 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
70 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
71 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
72 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileStatus;
73 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
74 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
75 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module;
76 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
77 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
78 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
79
80 class OrchestrationTemplateCandidateImplTest {
81
82     private final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateImplTest.class);
83     private final String candidateId = UUID.randomUUID().toString();
84     private final String softwareProductId = UUID.randomUUID().toString();
85     private final String versionId = UUID.randomUUID().toString();
86     private final String user = "cs0008";
87     @Mock
88     private OrchestrationTemplateCandidateManager candidateManager;
89     @Mock
90     private VendorSoftwareProductManager vendorSoftwareProductManager;
91     @Mock
92     private ActivityLogManager activityLogManager;
93     @Mock
94     private ArtifactStorageManager artifactStorageManager;
95     @Mock
96     private PackageSizeReducer packageSizeReducer;
97     @InjectMocks
98     private OrchestrationTemplateCandidateImpl orchestrationTemplateCandidate;
99
100     @BeforeEach
101     public void setUp() {
102         try {
103             MockitoAnnotations.openMocks(this);
104             UploadFileResponse uploadFileResponse = new UploadFileResponse();
105             uploadFileResponse.setOnboardingType(OnboardingTypesEnum.ZIP);
106             uploadFileResponse.setNetworkPackageName("test");
107             when(candidateManager.upload(any(), any())).thenReturn(uploadFileResponse);
108
109             // get using the candidate manager.
110             Optional<Pair<String, byte[]>> zipFile = Optional.of(Pair.of("Hello", "World".getBytes()));
111
112             when(candidateManager.get(
113                 ArgumentMatchers.eq(candidateId),
114                 ArgumentMatchers.any())).thenReturn(zipFile);
115
116             when(vendorSoftwareProductManager.get(
117                 ArgumentMatchers.eq(softwareProductId),
118                 ArgumentMatchers.any())).thenReturn(zipFile);
119
120             OrchestrationTemplateActionResponse processResponse = new OrchestrationTemplateActionResponse();
121             processResponse.setStatus(UploadFileStatus.Success);
122             when(candidateManager.process(
123                 ArgumentMatchers.eq(candidateId),
124                 ArgumentMatchers.any())).thenReturn(processResponse);
125
126             ValidationResponse vr = new ValidationResponse();
127             when(candidateManager.updateFilesDataStructure(
128                 ArgumentMatchers.eq(candidateId),
129                 ArgumentMatchers.any(),
130                 ArgumentMatchers.any())).thenReturn(vr);
131
132             FilesDataStructure fds = new FilesDataStructure();
133             fds.setArtifacts(Arrays.asList("a", "b"));
134             fds.setNested(Arrays.asList("foo", "bar"));
135             fds.setUnassigned(Arrays.asList("c", "d"));
136             fds.setModules(Arrays.asList(new Module(), new Module()));
137
138             when(candidateManager.getFilesDataStructure(
139                 ArgumentMatchers.eq(candidateId),
140                 ArgumentMatchers.any())).thenReturn(Optional.of(fds));
141
142         } catch (Exception e) {
143             logger.error(e.getMessage(), e);
144         }
145     }
146
147     @Test
148     void uploadSignedTest() throws IOException {
149         Response response = orchestrationTemplateCandidate
150             .upload("1", "1", mockAttachment("filename.zip", this.getClass().getResource("/files/sample-signed.zip")), user);
151         assertEquals(Status.OK.getStatusCode(), response.getStatus());
152         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
153     }
154
155     @Test
156     void uploadNotSignedTest() throws IOException {
157         Response response = orchestrationTemplateCandidate.upload("1", "1",
158             mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
159         assertEquals(Status.OK.getStatusCode(), response.getStatus());
160         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
161     }
162
163     @Test
164     void uploadNotSignedArtifactStorageManagerIsEnabledTest() throws IOException {
165         when(artifactStorageManager.isEnabled()).thenReturn(true);
166         when(artifactStorageManager.getStorageConfiguration()).thenReturn(
167             new MinIoStorageArtifactStorageConfig(true, new EndPoint("host", 9000, false), new Credentials("accessKey", "secretKey"), "tempPath"));
168
169         final Path path = Path.of("src/test/resources/files/sample-not-signed.csar");
170         when(artifactStorageManager.upload(anyString(), anyString(), any())).thenReturn(new MinIoArtifactInfo("vspId", "name"));
171         final byte[] bytes = Files.readAllBytes(path);
172         when(packageSizeReducer.reduce(any())).thenReturn(bytes);
173
174         Response response = orchestrationTemplateCandidate.upload("1", "1",
175             mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
176         assertEquals(Status.OK.getStatusCode(), response.getStatus());
177         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
178     }
179
180     private Attachment mockAttachment(final String fileName, final URL fileToUpload) throws IOException {
181         final Attachment attachment = Mockito.mock(Attachment.class);
182         final InputStream inputStream = Mockito.mock(InputStream.class);
183         when(attachment.getContentDisposition()).thenReturn(new ContentDisposition("test"));
184         final DataHandler dataHandler = Mockito.mock(DataHandler.class);
185         when(dataHandler.getName()).thenReturn(fileName);
186         when(attachment.getDataHandler()).thenReturn(dataHandler);
187         when(dataHandler.getInputStream()).thenReturn(inputStream);
188         when(inputStream.transferTo(any(OutputStream.class))).thenReturn(0L);
189         byte[] bytes = "upload package Test".getBytes();
190         if (Objects.nonNull(fileToUpload)) {
191             try {
192                 bytes = IOUtils.toByteArray(fileToUpload);
193             } catch (final IOException e) {
194                 logger.error("unexpected exception", e);
195                 fail("Not able to convert file to byte array");
196             }
197         }
198         when(attachment.getObject(ArgumentMatchers.any())).thenReturn(bytes);
199         return attachment;
200     }
201
202     @Test
203     void uploadSignNotValidTest() throws IOException {
204         Response response = orchestrationTemplateCandidate
205             .upload("1", "1", mockAttachment("filename.zip", null), user);
206         assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
207         assertFalse(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
208     }
209
210     @Test
211     void testCandidateGet() throws IOException {
212         Response rsp = orchestrationTemplateCandidate.get(candidateId, versionId, user);
213         assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
214         assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Candidate"), -1);
215         byte[] content = (byte[]) rsp.getEntity();
216         assertEquals("World", new String(content));
217     }
218
219     @Test
220     void testVendorSoftwareProductGet() throws IOException {
221         Response rsp = orchestrationTemplateCandidate.get(softwareProductId, versionId, user);
222         assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
223         assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Processed"), -1);
224         byte[] content = (byte[]) rsp.getEntity();
225         assertEquals("World", new String(content));
226     }
227
228     @Test
229     void testMissingGet() throws IOException {
230         Response rsp = orchestrationTemplateCandidate.get(UUID.randomUUID().toString(), versionId, user);
231         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rsp.getStatus(), "Response status equals");
232     }
233
234     @Test
235     void testAbort() {
236         try {
237             Response rsp = orchestrationTemplateCandidate.abort(candidateId, versionId);
238             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
239             assertNull(rsp.getEntity());
240         } catch (Exception ex) {
241             logger.error("unexpected exception", ex);
242             fail("abort should not throw an exception");
243         }
244     }
245
246     @Test
247     void testProcess() {
248         try {
249             Response rsp = orchestrationTemplateCandidate.process(candidateId, versionId, user);
250             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
251             assertNotNull(rsp.getEntity());
252             OrchestrationTemplateActionResponseDto dto = (OrchestrationTemplateActionResponseDto) rsp.getEntity();
253             assertEquals(UploadFileStatus.Success, dto.getStatus(), "status check");
254         } catch (Exception ex) {
255             logger.error("unexpected exception", ex);
256             fail("abort should not throw an exception");
257         }
258     }
259
260     @Test
261     void testFilesDataStructureUpload() {
262         try {
263             FileDataStructureDto dto = new FileDataStructureDto();
264             dto.setArtifacts(Arrays.asList("a", "b", "c"));
265             Response rsp = orchestrationTemplateCandidate.updateFilesDataStructure(candidateId, versionId, dto, user);
266             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
267         } catch (Exception ex) {
268             logger.error("unexpected exception", ex);
269             fail("abort should not throw an exception");
270         }
271     }
272
273     @Test
274     void testFilesDataStructureGet() {
275         try {
276             FileDataStructureDto dto = new FileDataStructureDto();
277             dto.setArtifacts(Arrays.asList("a", "b", "c"));
278             Response rsp = orchestrationTemplateCandidate.getFilesDataStructure(candidateId, versionId, user);
279             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
280         } catch (Exception ex) {
281             logger.error("unexpected exception", ex);
282             fail("abort should not throw an exception");
283         }
284     }
285
286 }