Add JUnit test for invalid TOSCA mappings JSON
[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.Matchers.is;
25 import static org.junit.Assert.assertThat;
26
27 import com.google.gson.Gson;
28 import java.io.IOException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.security.cert.X509Certificate;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.Map.Entry;
35 import javax.inject.Inject;
36 import javax.security.auth.x500.X500Principal;
37 import javax.ws.rs.core.HttpHeaders;
38 import javax.ws.rs.core.MultivaluedHashMap;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriInfo;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.junit.runner.RunWith;
44 import org.mockito.Mockito;
45 import org.onap.aai.auth.AAIMicroServiceAuth;
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         System.setProperty("CONFIG_HOME", "src/test/resources");
63     }
64
65     @Inject
66     private AAIMicroServiceAuth auth;
67
68     @BeforeClass
69     public static void setup() {
70         new ArtifactTestUtils().setGeneratorSystemProperties();
71     }
72
73     @Test
74     public void testGenerateArtifacts() throws Exception {
75         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR);
76         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
77         assertThat(response.getEntity(), is(getResponseJson("response.json")));
78     }
79
80     /**
81      * No VNF Configuration exists.
82      * 
83      * @throws URISyntaxException
84      *             if the URI cannot be created
85      * @throws IOException
86      *             if the resource cannot be loaded
87      */
88     @Test
89     public void testGenerateArtifactsWithoutVnfConfiguration() throws IOException, URISyntaxException {
90         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR);
91         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
92         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
93     }
94
95     @Test
96     public void testInvalidCsarFile() throws URISyntaxException, IOException {
97         BabelRequest request = new BabelRequest();
98         request.setArtifactName("hello");
99         request.setArtifactVersion("1.0");
100         request.setCsar("xxxx");
101         Response response = invokeService(new Gson().toJson(request));
102         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
103         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
104     }
105
106     @Test
107     public void testInvalidJsonFile() throws URISyntaxException, IOException {
108         Response response = invokeService("{\"csar:\"xxxx\"");
109         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
110         assertThat(response.getEntity(), is("Malformed request."));
111     }
112
113     @Test
114     public void testMissingArtifactName() throws Exception {
115         BabelRequest request = new BabelRequest();
116         request.setArtifactVersion("1.0");
117         request.setCsar("");
118         Response response = invokeService(new Gson().toJson(request));
119         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
120         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
121     }
122
123     @Test
124     public void testMissingArtifactVersion() throws Exception {
125         BabelRequest request = new BabelRequest();
126         request.setArtifactName("hello");
127         request.setCsar("");
128         Response response = invokeService(new Gson().toJson(request));
129         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
130         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
131     }
132
133     @Test
134     public void testMissingCsarFile() throws Exception {
135         BabelRequest request = new BabelRequest();
136         request.setArtifactName("test-name");
137         request.setArtifactVersion("1.0");
138         Response response = invokeService(new Gson().toJson(request));
139         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
140         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
141     }
142
143     /**
144      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
145      *
146      * @param csar
147      *            test CSAR file
148      * @return the Response from the HTTP API
149      * @throws URISyntaxException
150      *             if the URI cannot be created
151      * @throws IOException
152      *             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
163      *            the JSON request
164      * @return the Response from the HTTP API
165      * @throws URISyntaxException
166      *             if the URI cannot be created
167      */
168     private Response invokeService(String jsonString) throws URISyntaxException {
169         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
170         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
171         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
172         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
173
174         // Create mocked request headers map
175         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
176         headersMap.put("X-TransactionId", createSingletonList("transaction-id"));
177         headersMap.put("X-FromAppId", createSingletonList("app-id"));
178         headersMap.put("Host", createSingletonList("hostname"));
179
180         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
181         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
182             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
183         }
184         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
185
186         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
187         servletRequest.setSecure(true);
188         servletRequest.setScheme("https");
189         servletRequest.setServerPort(9501);
190         servletRequest.setServerName("localhost");
191         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
192
193         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
194         Mockito.when(mockCertificate.getSubjectX500Principal())
195                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
196
197         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
198         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
199
200         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
201         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
202     }
203
204     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
205         return new ArtifactTestUtils().getResponseJson(jsonResponse);
206     }
207
208     private List<String> createSingletonList(String listItem) {
209         return Collections.<String>singletonList(listItem);
210     }
211
212 }