Additional tests for VNF image extraction
[aai/babel.git] / src / test / java / org / onap / aai / babel / service / TestGenerateArtifactsServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.babel.service;
22
23 import static org.hamcrest.Matchers.is;
24 import static org.junit.Assert.assertThat;
25
26 import com.google.gson.Gson;
27 import java.io.IOException;
28 import java.net.URI;
29 import java.net.URISyntaxException;
30 import java.security.cert.X509Certificate;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Map.Entry;
34 import javax.inject.Inject;
35 import javax.security.auth.x500.X500Principal;
36 import javax.ws.rs.core.HttpHeaders;
37 import javax.ws.rs.core.MultivaluedHashMap;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.UriInfo;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.junit.runner.RunWith;
43 import org.mockito.Mockito;
44 import org.onap.aai.auth.AAIMicroServiceAuth;
45 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
46 import org.onap.aai.babel.service.data.BabelRequest;
47 import org.onap.aai.babel.testdata.CsarTest;
48 import org.onap.aai.babel.util.ArtifactTestUtils;
49 import org.springframework.mock.web.MockHttpServletRequest;
50 import org.springframework.test.context.ContextConfiguration;
51 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
52
53 /**
54  * Direct invocation of the generate artifacts service implementation.
55  *
56  */
57 @RunWith(SpringJUnit4ClassRunner.class)
58 @ContextConfiguration(locations = {"classpath:/babel-beans.xml"})
59 public class TestGenerateArtifactsServiceImpl {
60
61     static {
62         if (System.getProperty("APP_HOME") == null) {
63             System.setProperty("APP_HOME", ".");
64         }
65         System.setProperty("CONFIG_HOME", "src/test/resources");
66     }
67
68     private static final String ARTIFACT_GENERATOR_CONFIG = "artifact-generator.properties";
69
70     @Inject
71     private AAIMicroServiceAuth auth;
72
73     @BeforeClass
74     public static void setup() {
75         System.setProperty(ArtifactGeneratorToscaParser.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE,
76                 new ArtifactTestUtils().getResourcePath(ARTIFACT_GENERATOR_CONFIG));
77     }
78
79     @Test
80     public void testGenerateArtifacts() throws Exception {
81         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR);
82         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
83         assertThat(response.getEntity(), is(getResponseJson("response.json")));
84     }
85
86     /**
87      * No VNF Configuration exists.
88      *
89      * @throws Exception
90      */
91     @Test
92     public void testGenerateArtifactsWithoutVnfConfiguration() throws Exception {
93         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR);
94         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
95         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
96     }
97
98     @Test
99     public void testInvalidCsarFile() throws URISyntaxException, IOException {
100         BabelRequest request = new BabelRequest();
101         request.setArtifactName("hello");
102         request.setArtifactVersion("1.0");
103         request.setCsar("xxxx");
104         Response response = invokeService(new Gson().toJson(request));
105         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
106         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
107     }
108
109     @Test
110     public void testInvalidJsonFile() throws URISyntaxException, IOException {
111         Response response = invokeService("{\"csar:\"xxxx\"");
112         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
113         assertThat(response.getEntity(), is("Malformed request."));
114     }
115
116     @Test
117     public void testMissingArtifactName() throws Exception {
118         BabelRequest request = new BabelRequest();
119         request.setArtifactVersion("1.0");
120         request.setCsar("");
121         Response response = invokeService(new Gson().toJson(request));
122         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
123         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
124     }
125
126     @Test
127     public void testMissingArtifactVersion() throws Exception {
128         BabelRequest request = new BabelRequest();
129         request.setArtifactName("hello");
130         request.setCsar("");
131         Response response = invokeService(new Gson().toJson(request));
132         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
133         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
134     }
135
136     @Test
137     public void testMissingCsarFile() throws Exception {
138         BabelRequest request = new BabelRequest();
139         request.setArtifactName("test-name");
140         request.setArtifactVersion("1.0");
141         Response response = invokeService(new Gson().toJson(request));
142         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
143         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
144     }
145
146     /**
147      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
148      *
149      * @param csar
150      * @return the Response from the HTTP API
151      * @throws URISyntaxException if the URI cannot be created
152      * @throws IOException if the resource cannot be loaded
153      */
154     private Response processJsonRequest(CsarTest csar) throws IOException, URISyntaxException {
155         String jsonString = csar.getJsonRequest();
156         return invokeService(jsonString);
157     }
158
159     /**
160      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
161      *
162      * @param jsonString the JSON request
163      * @return the Response from the HTTP API
164      * @throws URISyntaxException if the URI cannot be created
165      */
166     private Response invokeService(String jsonString) throws URISyntaxException {
167         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
168         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
169         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
170         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
171
172         // Create mocked request headers map
173         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
174         headersMap.put("X-TransactionId", createSingletonList("transaction-id"));
175         headersMap.put("X-FromAppId", createSingletonList("app-id"));
176         headersMap.put("Host", createSingletonList("hostname"));
177
178         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
179         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
180             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
181         }
182         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
183
184         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
185         servletRequest.setSecure(true);
186         servletRequest.setScheme("https");
187         servletRequest.setServerPort(9501);
188         servletRequest.setServerName("localhost");
189         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
190
191         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
192         Mockito.when(mockCertificate.getSubjectX500Principal())
193                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
194
195         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
196         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
197
198         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
199         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
200     }
201
202     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
203         return new ArtifactTestUtils().getResponseJson(jsonResponse);
204     }
205
206     private List<String> createSingletonList(String listItem) {
207         return Collections.<String>singletonList(listItem);
208     }
209
210 }