4cc8c8ca1a0852d8d6bba913e9b0b43954ec8ace
[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 java.io.IOException;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.security.cert.X509Certificate;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map.Entry;
33 import javax.inject.Inject;
34 import javax.security.auth.x500.X500Principal;
35 import javax.ws.rs.core.HttpHeaders;
36 import javax.ws.rs.core.MultivaluedHashMap;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.UriInfo;
39 import org.junit.BeforeClass;
40 import org.junit.Test;
41 import org.junit.runner.RunWith;
42 import org.mockito.Mockito;
43 import org.onap.aai.auth.AAIMicroServiceAuth;
44 import org.onap.aai.babel.util.ArtifactTestUtils;
45 import org.onap.aai.babel.xml.generator.data.GeneratorConstants;
46 import org.springframework.mock.web.MockHttpServletRequest;
47 import org.springframework.test.context.ContextConfiguration;
48 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
49
50 /**
51  * Direct invocation of the generate artifacts service implementation
52  *
53  */
54 @RunWith(SpringJUnit4ClassRunner.class)
55 @ContextConfiguration(locations = { "classpath:/babel-beans.xml" })
56 public class TestGenerateArtifactsServiceImpl {
57
58     static {
59         if (System.getProperty("APP_HOME") == null) {
60             System.setProperty("APP_HOME", ".");
61         }
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         System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE,
71                 new ArtifactTestUtils().getResourcePath("artifact-generator.properties"));
72     }
73
74     @Test
75     public void testInvalidCsarFile() throws URISyntaxException, IOException {
76         Response response = processJsonRequest("invalid_csar_request.json");
77         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
78         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
79     }
80
81     @Test
82     public void testInvalidJsonFile() throws URISyntaxException, IOException {
83         Response response = processJsonRequest("invalid_json_request.json");
84         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
85         assertThat(response.getEntity(), is("Malformed request."));
86     }
87
88     @Test
89     public void testMissingArtifactName() throws Exception {
90         Response response = processJsonRequest("missing_artifact_name_request.json");
91         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
92         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
93     }
94
95     @Test
96     public void testMissingArtifactVersion() throws Exception {
97         Response response = processJsonRequest("missing_artifact_version_request.json");
98         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
99         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
100     }
101
102     @Test
103     public void testMissingCsarFile() throws Exception {
104         Response response = processJsonRequest("missing_csar_request.json");
105         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
106         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
107     }
108
109     /**
110      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API
111      *
112      * @param resource
113      *            path to the incoming JSON request
114      * @return the Response from the HTTP API
115      * @throws URISyntaxException
116      * @throws IOException
117      */
118     private Response processJsonRequest(String resource) throws URISyntaxException, IOException {
119         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
120         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
121         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
122         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
123
124         // Create mocked request headers map
125         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
126         headersMap.put("X-TransactionId", createSingletonList("transaction-id"));
127         headersMap.put("X-FromAppId", createSingletonList("app-id"));
128         headersMap.put("Host", createSingletonList("hostname"));
129
130         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
131         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
132             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
133         }
134         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
135
136         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
137         servletRequest.setSecure(true);
138         servletRequest.setScheme("https");
139         servletRequest.setServerPort(9501);
140         servletRequest.setServerName("localhost");
141         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
142
143         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
144         Mockito.when(mockCertificate.getSubjectX500Principal())
145                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
146
147         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] { mockCertificate });
148         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
149
150         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
151         String jsonString = getRequestJson(resource);
152         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
153     }
154
155     private String getRequestJson(String resource) throws IOException, URISyntaxException {
156         return new ArtifactTestUtils().getRequestJson(resource);
157     }
158
159     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
160         return new ArtifactTestUtils().getResponseJson(jsonResponse);
161     }
162
163     private List<String> createSingletonList(String listItem) {
164         return Collections.<String>singletonList(listItem);
165     }
166
167 }