78e02f4d4134c5b69022983314a98533d3e0f854
[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     private static final String FILTER_TYPES_CONFIG = "filter-types.properties";
70
71     @Inject
72     private AAIMicroServiceAuth auth;
73
74     @BeforeClass
75     public static void setup() {
76         System.setProperty(ArtifactGeneratorToscaParser.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE,
77                 new ArtifactTestUtils().getResourcePath(ARTIFACT_GENERATOR_CONFIG));
78         System.setProperty(ArtifactGeneratorToscaParser.PROPERTY_GROUP_FILTERS_CONFIG_FILE,
79                 new ArtifactTestUtils().getResourcePath(FILTER_TYPES_CONFIG));
80     }
81
82     @Test
83     public void testGenerateArtifacts() throws Exception {
84         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR);
85         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
86         assertThat(response.getEntity(), is(getResponseJson("response.json")));
87     }
88
89     /**
90      * No VNF Configuration exists.
91      *
92      * @throws Exception
93      */
94     @Test
95     public void testGenerateArtifactsWithoutVnfConfiguration() throws Exception {
96         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR);
97         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
98         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
99     }
100
101     @Test
102     public void testInvalidCsarFile() throws URISyntaxException, IOException {
103         BabelRequest request = new BabelRequest();
104         request.setArtifactName("hello");
105         request.setArtifactVersion("1.0");
106         request.setCsar("xxxx");
107         Response response = invokeService(new Gson().toJson(request));
108         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
109         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
110     }
111
112     @Test
113     public void testInvalidJsonFile() throws URISyntaxException, IOException {
114         Response response = invokeService("{\"csar:\"xxxx\"");
115         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
116         assertThat(response.getEntity(), is("Malformed request."));
117     }
118
119     @Test
120     public void testMissingArtifactName() throws Exception {
121         BabelRequest request = new BabelRequest();
122         request.setArtifactVersion("1.0");
123         request.setCsar("");
124         Response response = invokeService(new Gson().toJson(request));
125         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
126         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
127     }
128
129     @Test
130     public void testMissingArtifactVersion() throws Exception {
131         BabelRequest request = new BabelRequest();
132         request.setArtifactName("hello");
133         request.setCsar("");
134         Response response = invokeService(new Gson().toJson(request));
135         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
136         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
137     }
138
139     @Test
140     public void testMissingCsarFile() throws Exception {
141         BabelRequest request = new BabelRequest();
142         request.setArtifactName("test-name");
143         request.setArtifactVersion("1.0");
144         Response response = invokeService(new Gson().toJson(request));
145         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
146         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
147     }
148
149     /**
150      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
151      *
152      * @param csar
153      * @return the Response from the HTTP API
154      * @throws URISyntaxException
155      *             if the URI cannot be created
156      * @throws IOException
157      *             if the resource cannot be loaded
158      */
159     private Response processJsonRequest(CsarTest csar) throws IOException, URISyntaxException {
160         String jsonString = csar.getJsonRequest();
161         return invokeService(jsonString);
162     }
163
164     /**
165      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
166      *
167      * @param jsonString
168      *            the JSON request
169      * @return the Response from the HTTP API
170      * @throws URISyntaxException
171      *             if the URI cannot be created
172      */
173     private Response invokeService(String jsonString) throws URISyntaxException {
174         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
175         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
176         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
177         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
178
179         // Create mocked request headers map
180         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
181         headersMap.put("X-TransactionId", createSingletonList("transaction-id"));
182         headersMap.put("X-FromAppId", createSingletonList("app-id"));
183         headersMap.put("Host", createSingletonList("hostname"));
184
185         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
186         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
187             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
188         }
189         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
190
191         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
192         servletRequest.setSecure(true);
193         servletRequest.setScheme("https");
194         servletRequest.setServerPort(9501);
195         servletRequest.setServerName("localhost");
196         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
197
198         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
199         Mockito.when(mockCertificate.getSubjectX500Principal())
200                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
201
202         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] { mockCertificate });
203         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
204
205         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
206         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
207     }
208
209     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
210         return new ArtifactTestUtils().getResponseJson(jsonResponse);
211     }
212
213     private List<String> createSingletonList(String listItem) {
214         return Collections.<String>singletonList(listItem);
215     }
216
217 }