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