081f235db10054af71eff4237772320e1552d264
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.apihandlerinfra;
22
23
24 import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
25 import static com.github.tomakehurst.wiremock.client.WireMock.get;
26 import static com.github.tomakehurst.wiremock.client.WireMock.post;
27 import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
28 import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
29 import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
30 import static org.junit.Assert.assertEquals;
31 import static org.junit.Assert.assertThat;
32 import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID;
33 import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
34 import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME;
35 import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID;
36 import java.io.File;
37 import java.io.IOException;
38 import java.net.MalformedURLException;
39 import java.net.URL;
40 import java.nio.file.Files;
41 import java.nio.file.Paths;
42 import javax.ws.rs.core.MediaType;
43 import javax.ws.rs.core.Response;
44 import org.apache.http.HttpStatus;
45 import org.junit.Before;
46 import org.junit.Test;
47 import org.onap.logging.ref.slf4j.ONAPLogConstants;
48 import org.onap.so.db.request.beans.InfraActiveRequests;
49 import org.onap.so.logger.HttpHeadersConstants;
50 import org.onap.so.serviceinstancebeans.RequestReferences;
51 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.http.HttpEntity;
55 import org.springframework.http.HttpHeaders;
56 import org.springframework.http.HttpMethod;
57 import org.springframework.http.ResponseEntity;
58 import org.springframework.util.ResourceUtils;
59 import org.springframework.web.util.UriComponentsBuilder;
60 import com.fasterxml.jackson.databind.DeserializationFeature;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62
63 public class InstanceManagementTest extends BaseTest {
64
65     private final ObjectMapper mapper = new ObjectMapper();
66     private ObjectMapper errorMapper = new ObjectMapper();
67
68     @Autowired
69     InstanceManagement instanceManagement;
70
71     @Value("${wiremock.server.port}")
72     private String wiremockPort;
73
74     private final String instanceManagementUri = "/onap/so/infra/instanceManagement/";
75
76     private String uri;
77     private URL selfLink;
78     private URL initialUrl;
79     private int initialPort;
80     private HttpHeaders headers;
81
82     @Before
83     public void beforeClass() {
84         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
85         errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
86         errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
87         // set headers
88         headers = new HttpHeaders();
89         headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
90         headers.set(TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
91         headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
92         headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
93         headers.set(ONAP_PARTNER_NAME, "VID");
94         headers.set(REQUESTOR_ID, "xxxxxx");
95         try { // generate one-time port number to avoid RANDOM port number later.
96             initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
97             initialPort = initialUrl.getPort();
98         } catch (MalformedURLException e) {
99             e.printStackTrace();
100         }
101         wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse()
102                 .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
103     }
104
105     public String inputStream(String JsonInput) throws IOException {
106         JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
107         return new String(Files.readAllBytes(Paths.get(JsonInput)));
108     }
109
110     private URL createExpectedSelfLink(String version, String requestId) {
111         System.out.println("createdUrl: " + initialUrl.toString());
112         try {
113             selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
114         } catch (MalformedURLException e) {
115             e.printStackTrace();
116         }
117         return selfLink;
118     }
119
120     private String getWiremockResponseForCatalogdb(String file) {
121         try {
122             File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file);
123             return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090",
124                     "localhost:" + wiremockPort);
125         } catch (IOException e) {
126             e.printStackTrace();
127             return null;
128         }
129
130     }
131
132     public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod,
133             HttpHeaders headers) {
134
135         if (!headers.containsKey(HttpHeaders.ACCEPT)) {
136             headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
137         }
138         if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
139             headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
140         }
141
142         UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));
143
144         HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
145
146         return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
147     }
148
149     public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
150         return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
151     }
152
153     @Test
154     public void executeCustomWorkflow() throws IOException {
155         wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingWorkflow"))
156                 .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
157                         .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
158
159         wireMockServer.stubFor(get(urlMatching(
160                 ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be"))
161                         .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
162                                 .withBody(getWiremockResponseForCatalogdb("workflow_Response.json"))
163                                 .withStatus(org.apache.http.HttpStatus.SC_OK)));
164
165         // expected response
166         ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
167         RequestReferences requestReferences = new RequestReferences();
168         requestReferences.setInstanceId("1882939");
169         requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
170         expectedResponse.setRequestReferences(requestReferences);
171         uri = instanceManagementUri + "v1"
172                 + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be";
173         ResponseEntity<String> response =
174                 sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers);
175
176         assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
177         ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
178         assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
179     }
180
181     @Test
182     public void executePNFCustomWorkflow() throws IOException {
183         wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingPNFWorkflow"))
184                 .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
185                         .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
186
187         wireMockServer.stubFor(get(urlMatching(
188                 ".*/workflow/search/findByArtifactUUID[?]artifactUUID=81526781-e55c-4cb7-adb3-97e09d9c76bf"))
189                         .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
190                                 .withBody(getWiremockResponseForCatalogdb("workflow_pnf_Response.json"))
191                                 .withStatus(org.apache.http.HttpStatus.SC_OK)));
192
193         // expected response
194         ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
195         RequestReferences requestReferences = new RequestReferences();
196         requestReferences.setInstanceId("1882939");
197         requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
198         expectedResponse.setRequestReferences(requestReferences);
199         uri = instanceManagementUri + "v1"
200                 + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testPnfName/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf";
201         ResponseEntity<String> response =
202                 sendRequest(inputStream("/ExecutePNFCustomWorkflow.json"), uri, HttpMethod.POST, headers);
203
204         assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
205
206         ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
207         assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
208     }
209
210     @Test
211     public void workflowAndOperationNameTest() {
212         wireMockServer.stubFor(get(urlMatching(
213                 ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be"))
214                         .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
215                                 .withBody(getWiremockResponseForCatalogdb("workflow_Response.json"))
216                                 .withStatus(org.apache.http.HttpStatus.SC_OK)));
217         InfraActiveRequests activeReq = new InfraActiveRequests();
218         activeReq =
219                 instanceManagement.setWorkflowNameAndOperationName(activeReq, "71526781-e55c-4cb7-adb3-97e09d9c76be");
220         assertEquals(activeReq.getWorkflowName(), "testingWorkflow");
221         assertEquals(activeReq.getOperationName(), "testOperation");
222     }
223 }