Onboarding upload control
[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.eq;
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 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspUploadStatusDto;
80
81 class OrchestrationTemplateCandidateImplTest {
82
83     private final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateImplTest.class);
84     private final String candidateId = UUID.randomUUID().toString();
85     private final String softwareProductId = UUID.randomUUID().toString();
86     private final String versionId = UUID.randomUUID().toString();
87     private final String user = "cs0008";
88     @Mock
89     private OrchestrationTemplateCandidateManager candidateManager;
90     @Mock
91     private VendorSoftwareProductManager vendorSoftwareProductManager;
92     @Mock
93     private ActivityLogManager activityLogManager;
94     @Mock
95     private ArtifactStorageManager artifactStorageManager;
96     @Mock
97     private PackageSizeReducer packageSizeReducer;
98     @Mock
99     private OrchestrationTemplateCandidateUploadManager orchestrationTemplateCandidateUploadManager;
100     @InjectMocks
101     private OrchestrationTemplateCandidateImpl orchestrationTemplateCandidate;
102
103     @BeforeEach
104     public void setUp() {
105         try {
106             MockitoAnnotations.openMocks(this);
107             UploadFileResponse uploadFileResponse = new UploadFileResponse();
108             uploadFileResponse.setOnboardingType(OnboardingTypesEnum.ZIP);
109             uploadFileResponse.setNetworkPackageName("test");
110             when(candidateManager.upload(any(), any())).thenReturn(uploadFileResponse);
111
112             // get using the candidate manager.
113             Optional<Pair<String, byte[]>> zipFile = Optional.of(Pair.of("Hello", "World".getBytes()));
114
115             when(candidateManager.get(
116                 ArgumentMatchers.eq(candidateId),
117                 ArgumentMatchers.any())).thenReturn(zipFile);
118
119             when(vendorSoftwareProductManager.get(
120                 ArgumentMatchers.eq(softwareProductId),
121                 ArgumentMatchers.any())).thenReturn(zipFile);
122
123             OrchestrationTemplateActionResponse processResponse = new OrchestrationTemplateActionResponse();
124             processResponse.setStatus(UploadFileStatus.Success);
125             when(candidateManager.process(
126                 ArgumentMatchers.eq(candidateId),
127                 ArgumentMatchers.any())).thenReturn(processResponse);
128
129             ValidationResponse vr = new ValidationResponse();
130             when(candidateManager.updateFilesDataStructure(
131                 ArgumentMatchers.eq(candidateId),
132                 ArgumentMatchers.any(),
133                 ArgumentMatchers.any())).thenReturn(vr);
134
135             FilesDataStructure fds = new FilesDataStructure();
136             fds.setArtifacts(Arrays.asList("a", "b"));
137             fds.setNested(Arrays.asList("foo", "bar"));
138             fds.setUnassigned(Arrays.asList("c", "d"));
139             fds.setModules(Arrays.asList(new Module(), new Module()));
140
141             when(candidateManager.getFilesDataStructure(
142                 ArgumentMatchers.eq(candidateId),
143                 ArgumentMatchers.any())).thenReturn(Optional.of(fds));
144
145         } catch (Exception e) {
146             logger.error(e.getMessage(), e);
147         }
148     }
149
150     @Test
151     void uploadSignedTest() throws IOException {
152         final String vspId = "vspId";
153         final String versionId = "versionId";
154         when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
155         Response response = orchestrationTemplateCandidate
156             .upload(vspId, versionId, mockAttachment("filename.zip", this.getClass().getResource("/files/sample-signed.zip")), user);
157         assertEquals(Status.OK.getStatusCode(), response.getStatus());
158         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
159     }
160
161     @Test
162     void uploadNotSignedTest() throws IOException {
163         final String vspId = "vspId";
164         final String versionId = "versionId";
165         when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
166         Response response = orchestrationTemplateCandidate.upload(vspId, versionId,
167             mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
168         assertEquals(Status.OK.getStatusCode(), response.getStatus());
169         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
170     }
171
172     @Test
173     void uploadNotSignedArtifactStorageManagerIsEnabledTest() throws IOException {
174         when(artifactStorageManager.isEnabled()).thenReturn(true);
175         when(artifactStorageManager.getStorageConfiguration()).thenReturn(
176             new MinIoStorageArtifactStorageConfig(true, new EndPoint("host", 9000, false), new Credentials("accessKey", "secretKey"), "tempPath"));
177
178         final Path path = Path.of("src/test/resources/files/sample-not-signed.csar");
179         final String vspId = "vspId";
180         final String versionId = "versionId";
181         when(artifactStorageManager.upload(eq(vspId), eq(versionId), any())).thenReturn(new MinIoArtifactInfo("vspId", "name"));
182         final byte[] bytes = Files.readAllBytes(path);
183         when(packageSizeReducer.reduce(any())).thenReturn(bytes);
184
185         when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
186
187         Response response = orchestrationTemplateCandidate.upload(vspId, versionId,
188             mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
189         assertEquals(Status.OK.getStatusCode(), response.getStatus());
190         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
191     }
192
193     private Attachment mockAttachment(final String fileName, final URL fileToUpload) throws IOException {
194         final Attachment attachment = Mockito.mock(Attachment.class);
195         final InputStream inputStream = Mockito.mock(InputStream.class);
196         when(attachment.getContentDisposition()).thenReturn(new ContentDisposition("test"));
197         final DataHandler dataHandler = Mockito.mock(DataHandler.class);
198         when(dataHandler.getName()).thenReturn(fileName);
199         when(attachment.getDataHandler()).thenReturn(dataHandler);
200         when(dataHandler.getInputStream()).thenReturn(inputStream);
201         when(inputStream.transferTo(any(OutputStream.class))).thenReturn(0L);
202         byte[] bytes = "upload package Test".getBytes();
203         if (Objects.nonNull(fileToUpload)) {
204             try {
205                 bytes = IOUtils.toByteArray(fileToUpload);
206             } catch (final IOException e) {
207                 logger.error("unexpected exception", e);
208                 fail("Not able to convert file to byte array");
209             }
210         }
211         when(attachment.getObject(ArgumentMatchers.any())).thenReturn(bytes);
212         return attachment;
213     }
214
215     @Test
216     void uploadSignNotValidTest() throws IOException {
217         Response response = orchestrationTemplateCandidate
218             .upload("1", "1", mockAttachment("filename.zip", null), user);
219         assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
220         assertFalse(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
221     }
222
223     @Test
224     void testCandidateGet() throws IOException {
225         Response rsp = orchestrationTemplateCandidate.get(candidateId, versionId, user);
226         assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
227         assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Candidate"), -1);
228         byte[] content = (byte[]) rsp.getEntity();
229         assertEquals("World", new String(content));
230     }
231
232     @Test
233     void testVendorSoftwareProductGet() throws IOException {
234         Response rsp = orchestrationTemplateCandidate.get(softwareProductId, versionId, user);
235         assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
236         assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Processed"), -1);
237         byte[] content = (byte[]) rsp.getEntity();
238         assertEquals("World", new String(content));
239     }
240
241     @Test
242     void testMissingGet() throws IOException {
243         Response rsp = orchestrationTemplateCandidate.get(UUID.randomUUID().toString(), versionId, user);
244         assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rsp.getStatus(), "Response status equals");
245     }
246
247     @Test
248     void testAbort() {
249         try {
250             Response rsp = orchestrationTemplateCandidate.abort(candidateId, versionId);
251             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
252             assertNull(rsp.getEntity());
253         } catch (Exception ex) {
254             logger.error("unexpected exception", ex);
255             fail("abort should not throw an exception");
256         }
257     }
258
259     @Test
260     void testProcess() {
261         try {
262             Response rsp = orchestrationTemplateCandidate.process(candidateId, versionId, user);
263             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
264             assertNotNull(rsp.getEntity());
265             OrchestrationTemplateActionResponseDto dto = (OrchestrationTemplateActionResponseDto) rsp.getEntity();
266             assertEquals(UploadFileStatus.Success, dto.getStatus(), "status check");
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 testFilesDataStructureUpload() {
275         try {
276             FileDataStructureDto dto = new FileDataStructureDto();
277             dto.setArtifacts(Arrays.asList("a", "b", "c"));
278             Response rsp = orchestrationTemplateCandidate.updateFilesDataStructure(candidateId, versionId, dto, 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     @Test
287     void testFilesDataStructureGet() {
288         try {
289             FileDataStructureDto dto = new FileDataStructureDto();
290             dto.setArtifacts(Arrays.asList("a", "b", "c"));
291             Response rsp = orchestrationTemplateCandidate.getFilesDataStructure(candidateId, versionId, user);
292             assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
293         } catch (Exception ex) {
294             logger.error("unexpected exception", ex);
295             fail("abort should not throw an exception");
296         }
297     }
298
299 }