GenerateArtifactsServiceImpl code coverage
[aai/babel.git] / src / test / java / org / onap / aai / babel / service / TestGenerateArtifactsServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright (c) 2017-2019 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
22 package org.onap.aai.babel.service;
23
24 import static org.hamcrest.CoreMatchers.containsString;
25 import static org.hamcrest.Matchers.is;
26 import static org.junit.Assert.assertThat;
27
28 import com.google.gson.Gson;
29 import java.io.IOException;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.security.cert.X509Certificate;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Optional;
37 import javax.inject.Inject;
38 import javax.security.auth.x500.X500Principal;
39 import javax.ws.rs.core.HttpHeaders;
40 import javax.ws.rs.core.MultivaluedHashMap;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.junit.runner.RunWith;
46 import org.mockito.Mockito;
47 import org.onap.aai.auth.AAIAuthException;
48 import org.onap.aai.auth.AAIMicroServiceAuth;
49 import org.onap.aai.babel.service.data.BabelRequest;
50 import org.onap.aai.babel.testdata.CsarTest;
51 import org.onap.aai.babel.util.ArtifactTestUtils;
52 import org.springframework.mock.web.MockHttpServletRequest;
53 import org.springframework.test.context.ContextConfiguration;
54 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
55
56 /**
57  * Direct invocation of the generate artifacts service implementation.
58  *
59  */
60 @RunWith(SpringJUnit4ClassRunner.class)
61 @ContextConfiguration(locations = {"classpath:/babel-beans.xml"})
62 public class TestGenerateArtifactsServiceImpl {
63
64     static {
65         System.setProperty("CONFIG_HOME", "src/test/resources");
66     }
67
68     @Inject
69     private AAIMicroServiceAuth auth;
70
71     @BeforeClass
72     public static void setup() {
73         new ArtifactTestUtils().setGeneratorSystemProperties();
74     }
75
76     /**
77      * Test with a valid request (and valid CSAR content) by calling the Service implementation directly using a mocked
78      * HTTPS request.
79      *
80      * @throws URISyntaxException
81      *             if the URI cannot be created
82      * @throws IOException
83      *             if the resource cannot be loaded
84      */
85     @Test
86     public void testGenerateArtifacts() throws URISyntaxException, IOException {
87         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR, auth);
88         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
89         assertThat(response.getEntity(), is(getResponseJson("response.json")));
90     }
91
92     /**
93      * Test with a valid request that has no Transaction ID header value.
94      *
95      * @throws URISyntaxException
96      *             if the URI cannot be created
97      * @throws IOException
98      *             if the resource cannot be loaded
99      */
100     @Test
101     public void testGenerateArtifactsWithoutRequestId() throws URISyntaxException, IOException {
102         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequest(), Optional.empty(), auth);
103         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
104         assertThat(response.getEntity(), is(getResponseJson("response.json")));
105     }
106
107     /**
108      * Test with a valid request, using a CSAR file that has no VNF configuration present.
109      *
110      * @throws URISyntaxException
111      *             if the URI cannot be created
112      * @throws IOException
113      *             if the resource cannot be loaded
114      */
115     @Test
116     public void testGenerateArtifactsWithoutVnfConfiguration() throws IOException, URISyntaxException {
117         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, auth);
118         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
119         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
120     }
121
122     /**
123      * Test for a valid request with invalid CSAR file content.
124      *
125      * @throws URISyntaxException
126      *             if the URI cannot be created
127      * @throws IOException
128      *             if the resource cannot be loaded
129      */
130     @Test
131     public void testGenerateArtifactsInvalidCsar() throws IOException, URISyntaxException {
132         Response response = processJsonRequest(CsarTest.MULTIPLE_VNF_CSAR, auth);
133         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
134         assertThat(response.getEntity().toString(), containsString("VNF catalog"));
135     }
136
137     @Test
138     public void testUninitializedService() throws IOException, URISyntaxException, AAIAuthException {
139         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
140         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
141                 .thenThrow(new AAIAuthException("test"));
142         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
143         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
144         assertThat(response.getEntity().toString(), containsString("check the Babel service logs"));
145     }
146
147     @Test
148     public void testUnauthorizedRequest() throws IOException, URISyntaxException, AAIAuthException {
149         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
150         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
151                 .thenReturn(false);
152         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
153         assertThat(response.getStatus(), is(Response.Status.UNAUTHORIZED.getStatusCode()));
154         assertThat(response.getEntity().toString(), containsString("User not authorized"));
155     }
156
157     @Test
158     public void testInvalidCsarFile() throws URISyntaxException, IOException {
159         BabelRequest request = new BabelRequest();
160         request.setArtifactName("hello");
161         request.setArtifactVersion("1.0");
162         request.setCsar("xxxx");
163         Response response = invokeService(new Gson().toJson(request));
164         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
165         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
166     }
167
168     @Test
169     public void testInvalidJsonFile() throws URISyntaxException, IOException {
170         Response response = invokeService("{\"csar:\"xxxx\"");
171         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
172         assertThat(response.getEntity(), is("Malformed request."));
173     }
174
175     @Test
176     public void testMissingArtifactName() throws Exception {
177         BabelRequest request = new BabelRequest();
178         request.setArtifactVersion("1.0");
179         request.setCsar("");
180         Response response = invokeService(new Gson().toJson(request));
181         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
182         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
183     }
184
185     @Test
186     public void testMissingArtifactVersion() throws Exception {
187         BabelRequest request = new BabelRequest();
188         request.setArtifactName("hello");
189         request.setCsar("");
190         Response response = invokeService(new Gson().toJson(request));
191         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
192         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
193     }
194
195     @Test
196     public void testMissingCsarFile() throws Exception {
197         BabelRequest request = new BabelRequest();
198         request.setArtifactName("test-name");
199         request.setArtifactVersion("1.0");
200         Response response = invokeService(new Gson().toJson(request));
201         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
202         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
203     }
204
205     /**
206      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
207      *
208      * @param csar
209      *            test CSAR file
210      * @param auth
211      *            the auth module
212      * @return the Response from the HTTP API
213      * @throws URISyntaxException
214      *             if the URI cannot be created
215      * @throws IOException
216      *             if the resource cannot be loaded
217      */
218     private Response processJsonRequest(CsarTest csar, AAIMicroServiceAuth auth)
219             throws URISyntaxException, IOException {
220         return invokeService(csar.getJsonRequest(), Optional.of("transaction-id"), auth);
221     }
222
223     /**
224      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
225      *
226      * @param jsonString
227      *            the JSON request
228      * @return the Response from the HTTP API
229      * @throws URISyntaxException
230      *             if the URI cannot be created
231      */
232     private Response invokeService(String jsonRequest) throws URISyntaxException {
233         return invokeService(jsonRequest, Optional.of("transaction-id"), auth);
234     }
235
236     /**
237      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
238      *
239      * @param jsonString
240      *            the JSON request
241      * @param transactionId
242      *            optional X-TransactionId value for the HTTP request
243      * @param auth
244      *            the auth module
245      * @return the Response from the HTTP API
246      * @throws URISyntaxException
247      *             if the URI cannot be created
248      */
249     private Response invokeService(String jsonString, Optional<String> transactionId, AAIMicroServiceAuth auth)
250             throws URISyntaxException {
251         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
252         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
253         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
254         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
255
256         // Create mocked request headers map
257         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
258         if (transactionId.isPresent()) {
259             headersMap.put("X-TransactionId", createSingletonList(transactionId.get()));
260         }
261         headersMap.put("X-FromAppId", createSingletonList("app-id"));
262         headersMap.put("Host", createSingletonList("hostname"));
263
264         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
265         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
266             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
267             Mockito.when(headers.getHeaderString(entry.getKey())).thenReturn(entry.getValue().get(0));
268         }
269         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
270
271         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
272         servletRequest.setSecure(true);
273         servletRequest.setScheme("https");
274         servletRequest.setServerPort(9501);
275         servletRequest.setServerName("localhost");
276         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
277
278         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
279         Mockito.when(mockCertificate.getSubjectX500Principal())
280                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
281
282         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
283         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
284
285         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
286         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
287     }
288
289     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
290         return new ArtifactTestUtils().getResponseJson(jsonResponse);
291     }
292
293     private List<String> createSingletonList(String listItem) {
294         return Collections.<String>singletonList(listItem);
295     }
296
297 }