146062533eb11bf4b1f0e6fe49e437df745b230b
[so.git] / mso-api-handlers / mso-api-handler-infra / src / test / java / org / onap / so / apihandlerinfra / InstanceManagementTest.java
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.stubFor;
28 import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
29 import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
30 import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
31 import static org.junit.Assert.assertEquals;
32 import static org.junit.Assert.assertThat;
33 import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
34 import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
35 import static org.onap.so.logger.MdcConstants.CLIENT_ID;
36
37 import java.io.File;
38 import java.io.IOException;
39 import java.net.MalformedURLException;
40 import java.net.URL;
41 import java.nio.file.Files;
42 import java.nio.file.Paths;
43
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46
47 import org.apache.http.HttpStatus;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.onap.logging.ref.slf4j.ONAPLogConstants;
51 import org.onap.so.logger.HttpHeadersConstants;
52 import org.onap.so.serviceinstancebeans.RequestReferences;
53 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.beans.factory.annotation.Value;
56 import org.springframework.http.HttpEntity;
57 import org.springframework.http.HttpHeaders;
58 import org.springframework.http.HttpMethod;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.util.ResourceUtils;
61 import org.springframework.web.util.UriComponentsBuilder;
62
63 import com.fasterxml.jackson.databind.DeserializationFeature;
64 import com.fasterxml.jackson.databind.ObjectMapper;
65
66 public class InstanceManagementTest extends BaseTest{
67
68         private final ObjectMapper mapper = new ObjectMapper();
69         private ObjectMapper errorMapper = new ObjectMapper();
70         
71     @Autowired
72     private InstanceManagement instanceManagement;
73     
74     @Value("${wiremock.server.port}")
75         private String wiremockPort;
76
77     private final String instanceManagementUri = "/onap/so/infra/instanceManagement/";
78
79     private String uri;
80     private URL selfLink;
81     private URL initialUrl;
82     private int initialPort;
83     private HttpHeaders headers;
84
85         @Before
86         public  void beforeClass() {
87                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
88                 errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
89                 errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
90         // set headers
91                 headers = new HttpHeaders();
92         headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");        
93                 headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
94         headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
95         headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
96         headers.set(CLIENT_ID, "VID");
97         headers.set(REQUESTOR_ID, "xxxxxx");
98                 try {  // generate one-time port number to avoid RANDOM port number later.
99                         initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
100                         initialPort = initialUrl.getPort();
101                 } catch (MalformedURLException e) {
102                         e.printStackTrace();
103                 } 
104                 stubFor(post(urlMatching(".*/infraActiveRequests.*"))
105                                 .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
106                                                 .withStatus(HttpStatus.SC_OK)));
107         }
108         
109     public String inputStream(String JsonInput)throws IOException{
110         JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
111         return new String(Files.readAllBytes(Paths.get(JsonInput)));
112     }
113
114     private URL createExpectedSelfLink(String version, String requestId) {
115         System.out.println("createdUrl: " + initialUrl.toString()); 
116                 try {   
117                         selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
118                 } catch (MalformedURLException e) {
119                         e.printStackTrace();
120                 }       
121         return selfLink;
122     }
123     
124         private String getWiremockResponseForCatalogdb(String file) {
125                 try {
126                         File resource= ResourceUtils.getFile("classpath:__files/catalogdb/"+file);
127                         return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090","localhost:"+wiremockPort);
128                 } catch (IOException e) {
129                         e.printStackTrace();
130                         return null;
131                 }
132
133         }
134         
135         public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){
136                 
137                 if (!headers.containsKey(HttpHeaders.ACCEPT)) {
138                         headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
139                 }
140                 if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
141                         headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON);
142                 }
143
144         UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));
145
146         HttpEntity<String> request = new HttpEntity<>(requestJson, headers);
147
148         return restTemplate.exchange(builder.toUriString(),
149                 reqMethod, request, String.class);
150     }
151         
152     public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){
153         return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
154     }
155
156     @Test
157     public void executeCustomWorkflow() throws IOException {
158         stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate"))
159                 .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
160                         .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));
161         
162         stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" +
163                 "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate"))
164                 .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
165                         .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json"))
166                         .withStatus(org.apache.http.HttpStatus.SC_OK)));
167
168         //expected response
169         ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
170         RequestReferences requestReferences = new RequestReferences();
171         requestReferences.setInstanceId("1882939");
172         requestReferences.setRequestSelfLink(createExpectedSelfLink("v1","32807a28-1a14-4b88-b7b3-2950918aa76d"));        
173         expectedResponse.setRequestReferences(requestReferences);
174         uri = instanceManagementUri + "v1" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be";
175         ResponseEntity<String> response = sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers);
176
177         assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
178         ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
179         assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); 
180     }
181 }