2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdcrests.vsp.rest.services;
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.assertThrows;
29 import static org.junit.jupiter.api.Assertions.assertTrue;
30 import static org.junit.jupiter.api.Assertions.fail;
31 import static org.mockito.ArgumentMatchers.any;
32 import static org.mockito.ArgumentMatchers.eq;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.OutputStream;
40 import java.nio.file.Files;
41 import java.nio.file.Path;
42 import java.util.Arrays;
43 import java.util.Objects;
44 import java.util.Optional;
45 import java.util.UUID;
46 import javax.activation.DataHandler;
47 import javax.ws.rs.core.Response;
48 import javax.ws.rs.core.Response.Status;
49 import org.apache.commons.io.IOUtils;
50 import org.apache.commons.lang3.tuple.Pair;
51 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
52 import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
53 import org.junit.jupiter.api.BeforeEach;
54 import org.junit.jupiter.api.Test;
55 import org.mockito.ArgumentMatchers;
56 import org.mockito.InjectMocks;
57 import org.mockito.Mock;
58 import org.mockito.Mockito;
59 import org.mockito.MockitoAnnotations;
60 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
61 import org.openecomp.sdc.activitylog.ActivityLogManager;
62 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
63 import org.openecomp.sdc.be.csar.storage.MinIoArtifactInfo;
64 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig;
65 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig.Credentials;
66 import org.openecomp.sdc.be.csar.storage.MinIoStorageArtifactStorageConfig.EndPoint;
67 import org.openecomp.sdc.be.csar.storage.PackageSizeReducer;
68 import org.openecomp.sdc.logging.api.Logger;
69 import org.openecomp.sdc.logging.api.LoggerFactory;
70 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
71 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspUploadStatus;
73 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
74 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
75 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileStatus;
76 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
77 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module;
79 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
80 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
81 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
82 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspUploadStatusDto;
84 class OrchestrationTemplateCandidateImplTest {
86 private final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateImplTest.class);
87 private final String candidateId = UUID.randomUUID().toString();
88 private final String softwareProductId = UUID.randomUUID().toString();
89 private final String versionId = UUID.randomUUID().toString();
90 private final String user = "cs0008";
92 private OrchestrationTemplateCandidateManager candidateManager;
94 private VendorSoftwareProductManager vendorSoftwareProductManager;
96 private ActivityLogManager activityLogManager;
98 private ArtifactStorageManager artifactStorageManager;
100 private PackageSizeReducer packageSizeReducer;
102 private OrchestrationTemplateCandidateUploadManager orchestrationTemplateCandidateUploadManager;
104 private OrchestrationTemplateCandidateImpl orchestrationTemplateCandidate;
107 public void setUp() {
109 MockitoAnnotations.openMocks(this);
110 UploadFileResponse uploadFileResponse = new UploadFileResponse();
111 uploadFileResponse.setOnboardingType(OnboardingTypesEnum.ZIP);
112 uploadFileResponse.setNetworkPackageName("test");
113 when(candidateManager.upload(any(), any())).thenReturn(uploadFileResponse);
115 // get using the candidate manager.
116 Optional<Pair<String, byte[]>> zipFile = Optional.of(Pair.of("Hello", "World".getBytes()));
118 when(candidateManager.get(
119 ArgumentMatchers.eq(candidateId),
120 ArgumentMatchers.any())).thenReturn(zipFile);
122 when(vendorSoftwareProductManager.get(
123 ArgumentMatchers.eq(softwareProductId),
124 ArgumentMatchers.any())).thenReturn(zipFile);
126 OrchestrationTemplateActionResponse processResponse = new OrchestrationTemplateActionResponse();
127 processResponse.setStatus(UploadFileStatus.Success);
128 when(candidateManager.process(
129 ArgumentMatchers.eq(candidateId),
130 ArgumentMatchers.any())).thenReturn(processResponse);
132 ValidationResponse vr = new ValidationResponse();
133 when(candidateManager.updateFilesDataStructure(
134 ArgumentMatchers.eq(candidateId),
135 ArgumentMatchers.any(),
136 ArgumentMatchers.any())).thenReturn(vr);
138 FilesDataStructure fds = new FilesDataStructure();
139 fds.setArtifacts(Arrays.asList("a", "b"));
140 fds.setNested(Arrays.asList("foo", "bar"));
141 fds.setUnassigned(Arrays.asList("c", "d"));
142 fds.setModules(Arrays.asList(new Module(), new Module()));
144 when(candidateManager.getFilesDataStructure(
145 ArgumentMatchers.eq(candidateId),
146 ArgumentMatchers.any())).thenReturn(Optional.of(fds));
148 } catch (Exception e) {
149 logger.error(e.getMessage(), e);
154 void uploadSignedTest() throws IOException {
155 final String vspId = "vspId";
156 final String versionId = "versionId";
157 when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
158 when(orchestrationTemplateCandidateUploadManager.putUploadInValidation(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
159 when(orchestrationTemplateCandidateUploadManager.putUploadInProcessing(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
160 Response response = orchestrationTemplateCandidate
161 .upload(vspId, versionId, mockAttachment("filename.zip", this.getClass().getResource("/files/sample-signed.zip")), user);
162 assertEquals(Status.OK.getStatusCode(), response.getStatus());
163 assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
167 void uploadNotSignedTest() throws IOException {
168 final String vspId = "vspId";
169 final String versionId = "versionId";
170 when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
171 when(orchestrationTemplateCandidateUploadManager.putUploadInValidation(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
172 when(orchestrationTemplateCandidateUploadManager.putUploadInProcessing(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
173 Response response = orchestrationTemplateCandidate.upload(vspId, versionId,
174 mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
175 assertEquals(Status.OK.getStatusCode(), response.getStatus());
176 assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
180 void uploadNotSignedArtifactStorageManagerIsEnabledTest() throws IOException {
181 when(artifactStorageManager.isEnabled()).thenReturn(true);
182 when(artifactStorageManager.getStorageConfiguration()).thenReturn(
183 new MinIoStorageArtifactStorageConfig(true, new EndPoint("host", 9000, false), new Credentials("accessKey", "secretKey"), "tempPath"));
185 final Path path = Path.of("src/test/resources/files/sample-not-signed.csar");
186 final String vspId = "vspId";
187 final String versionId = "versionId";
188 when(artifactStorageManager.upload(eq(vspId), eq(versionId), any())).thenReturn(new MinIoArtifactInfo("vspId", "name"));
189 final byte[] bytes = Files.readAllBytes(path);
190 when(packageSizeReducer.reduce(any())).thenReturn(bytes);
192 when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
193 when(orchestrationTemplateCandidateUploadManager.putUploadInValidation(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
194 when(orchestrationTemplateCandidateUploadManager.putUploadInProcessing(vspId, versionId, user)).thenReturn(new VspUploadStatusDto());
196 Response response = orchestrationTemplateCandidate.upload(vspId, versionId,
197 mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), user);
198 assertEquals(Status.OK.getStatusCode(), response.getStatus());
199 assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
202 private Attachment mockAttachment(final String fileName, final URL fileToUpload) throws IOException {
203 final Attachment attachment = Mockito.mock(Attachment.class);
204 final InputStream inputStream = Mockito.mock(InputStream.class);
205 when(attachment.getContentDisposition()).thenReturn(new ContentDisposition("test"));
206 final DataHandler dataHandler = Mockito.mock(DataHandler.class);
207 when(dataHandler.getName()).thenReturn(fileName);
208 when(attachment.getDataHandler()).thenReturn(dataHandler);
209 when(dataHandler.getInputStream()).thenReturn(inputStream);
210 when(inputStream.transferTo(any(OutputStream.class))).thenReturn(0L);
211 byte[] bytes = "upload package Test".getBytes();
212 if (Objects.nonNull(fileToUpload)) {
214 bytes = IOUtils.toByteArray(fileToUpload);
215 } catch (final IOException e) {
216 logger.error("unexpected exception", e);
217 fail("Not able to convert file to byte array");
220 when(attachment.getObject(ArgumentMatchers.any())).thenReturn(bytes);
225 void uploadSignNotValidTest() throws IOException {
227 when(orchestrationTemplateCandidateUploadManager.putUploadInValidation(candidateId, versionId, user)).thenReturn(new VspUploadStatusDto());
229 Response response = orchestrationTemplateCandidate
230 .upload(candidateId, versionId, mockAttachment("filename.zip", null), user);
232 assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
233 assertFalse(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
237 void testCandidateGet() throws IOException {
238 Response rsp = orchestrationTemplateCandidate.get(candidateId, versionId, user);
239 assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
240 assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Candidate"), -1);
241 byte[] content = (byte[]) rsp.getEntity();
242 assertEquals("World", new String(content));
246 void testVendorSoftwareProductGet() throws IOException {
247 Response rsp = orchestrationTemplateCandidate.get(softwareProductId, versionId, user);
248 assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
249 assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Processed"), -1);
250 byte[] content = (byte[]) rsp.getEntity();
251 assertEquals("World", new String(content));
255 void testMissingGet() throws IOException {
256 Response rsp = orchestrationTemplateCandidate.get(UUID.randomUUID().toString(), versionId, user);
257 assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rsp.getStatus(), "Response status equals");
263 Response rsp = orchestrationTemplateCandidate.abort(candidateId, versionId);
264 assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
265 assertNull(rsp.getEntity());
266 } catch (Exception ex) {
267 logger.error("unexpected exception", ex);
268 fail("abort should not throw an exception");
275 Response rsp = orchestrationTemplateCandidate.process(candidateId, versionId, user);
276 assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
277 assertNotNull(rsp.getEntity());
278 OrchestrationTemplateActionResponseDto dto = (OrchestrationTemplateActionResponseDto) rsp.getEntity();
279 assertEquals(UploadFileStatus.Success, dto.getStatus(), "status check");
280 } catch (Exception ex) {
281 logger.error("unexpected exception", ex);
282 fail("abort should not throw an exception");
287 void testFilesDataStructureUpload() {
289 FileDataStructureDto dto = new FileDataStructureDto();
290 dto.setArtifacts(Arrays.asList("a", "b", "c"));
291 Response rsp = orchestrationTemplateCandidate.updateFilesDataStructure(candidateId, versionId, dto, 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");
300 void testFilesDataStructureGet() {
302 FileDataStructureDto dto = new FileDataStructureDto();
303 dto.setArtifacts(Arrays.asList("a", "b", "c"));
304 Response rsp = orchestrationTemplateCandidate.getFilesDataStructure(candidateId, versionId, user);
305 assertEquals(Response.Status.OK.getStatusCode(), rsp.getStatus(), "Response status equals");
306 } catch (Exception ex) {
307 logger.error("unexpected exception", ex);
308 fail("abort should not throw an exception");
313 void finishUploadMustBeCalledWhenExceptionHappensTest() {
315 final VspUploadStatusDto vspUploadStatusDto = new VspUploadStatusDto();
316 vspUploadStatusDto.setLockId(UUID.randomUUID());
317 when(orchestrationTemplateCandidateUploadManager.putUploadInProgress(candidateId, versionId, user)).thenReturn(vspUploadStatusDto);
318 final RuntimeException forcedException = new RuntimeException();
319 when(artifactStorageManager.isEnabled()).thenThrow(forcedException);
320 final Attachment mock = Mockito.mock(Attachment.class);
321 when(mock.getDataHandler()).thenReturn(Mockito.mock(DataHandler.class));
323 final RuntimeException actualException = assertThrows(RuntimeException.class,
324 () -> orchestrationTemplateCandidate.upload(candidateId, versionId, mock, user));
326 assertEquals(forcedException, actualException);
327 verify(orchestrationTemplateCandidateUploadManager)
328 .putUploadAsFinished(candidateId, versionId, vspUploadStatusDto.getLockId(), VspUploadStatus.ERROR, user);