Incorporate the ECOMP SDC Artefact Generator code
[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.net.URL;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
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.stream.Collectors;
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.AAIMicroServiceAuth;
48 import org.onap.aai.babel.xml.generator.data.GeneratorConstants;
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("AJSC_HOME") == null) {
63             System.setProperty("AJSC_HOME", ".");
64         }
65     }
66
67     @Inject
68     private AAIMicroServiceAuth auth;
69
70     @BeforeClass
71     public static void setup() {
72         URL url = TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource("artifact-generator.properties");
73         System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath());
74     }
75
76     @Test
77     public void testInvalidCsarFile() throws URISyntaxException, IOException {
78         String jsonRequest = readstringFromFile("jsonFiles/invalid_csar_request.json");
79         Response response = processJsonRequest(jsonRequest);
80         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
81         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
82     }
83
84     @Test
85     public void testInvalidJsonFile() throws URISyntaxException, IOException {
86         String jsonRequest = readstringFromFile("jsonFiles/invalid_json_request.json");
87         Response response = processJsonRequest(jsonRequest);
88         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
89         assertThat(response.getEntity(), is("Malformed request."));
90     }
91
92     @Test
93     public void testMissingArtifactName() throws Exception {
94         String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_name_request.json");
95         Response response = processJsonRequest(jsonRequest);
96         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
97         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
98     }
99
100     @Test
101     public void testMissingArtifactVersion() throws Exception {
102         String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_version_request.json");
103         Response response = processJsonRequest(jsonRequest);
104         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
105         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
106     }
107
108     @Test
109     public void testMissingCsarFile() throws Exception {
110         String jsonRequest = readstringFromFile("jsonFiles/missing_csar_request.json");
111         Response response = processJsonRequest(jsonRequest);
112         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
113         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
114     }
115
116     /**
117      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API
118      * 
119      * @param request for the Babel Service
120      * @return the Response from the HTTP API
121      * @throws URISyntaxException
122      */
123     private Response processJsonRequest(String jsonRequest) throws URISyntaxException {
124         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
125         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
126         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
127         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
128
129         // Create mocked request headers map
130         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
131         headersMap.put("X-TransactionId", createSingletonList("transaction-id"));
132         headersMap.put("X-FromAppId", createSingletonList("app-id"));
133         headersMap.put("Host", createSingletonList("hostname"));
134
135         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
136         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
137             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
138         }
139         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
140
141         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
142         servletRequest.setSecure(true);
143         servletRequest.setScheme("https");
144         servletRequest.setServerPort(9501);
145         servletRequest.setServerName("localhost");
146         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
147
148         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
149         Mockito.when(mockCertificate.getSubjectX500Principal())
150                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
151
152         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
153         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
154
155         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
156         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonRequest);
157     }
158
159     private List<String> createSingletonList(String listItem) {
160         return Collections.<String>singletonList(listItem);
161     }
162
163     private String readstringFromFile(String resourceFile) throws IOException, URISyntaxException {
164         return Files
165                 .lines(Paths
166                         .get(TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource(resourceFile).toURI()))
167                 .collect(Collectors.joining());
168     }
169
170 }