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