summaryrefslogtreecommitdiffstats
path: root/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java
blob: 9fc9e4a51b1d4070ad2e2be73458ff57142e0e82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.so.apihandlerinfra;


import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
import static org.onap.so.logger.MdcConstants.CLIENT_ID;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.logger.HttpHeadersConstants;
import org.onap.so.serviceinstancebeans.RequestReferences;
import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class InstanceManagementTest extends BaseTest {

    private final ObjectMapper mapper = new ObjectMapper();
    private ObjectMapper errorMapper = new ObjectMapper();

    @Value("${wiremock.server.port}")
    private String wiremockPort;

    private final String instanceManagementUri = "/onap/so/infra/instanceManagement/";

    private String uri;
    private URL selfLink;
    private URL initialUrl;
    private int initialPort;
    private HttpHeaders headers;

    @Before
    public void beforeClass() {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        // set headers
        headers = new HttpHeaders();
        headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name");
        headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
        headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
        headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d");
        headers.set(CLIENT_ID, "VID");
        headers.set(REQUESTOR_ID, "xxxxxx");
        try { // generate one-time port number to avoid RANDOM port number later.
            initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH));
            initialPort = initialUrl.getPort();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse()
                .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK)));
    }

    public String inputStream(String JsonInput) throws IOException {
        JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput;
        return new String(Files.readAllBytes(Paths.get(JsonInput)));
    }

    private URL createExpectedSelfLink(String version, String requestId) {
        System.out.println("createdUrl: " + initialUrl.toString());
        try {
            selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return selfLink;
    }

    private String getWiremockResponseForCatalogdb(String file) {
        try {
            File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file);
            return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090",
                    "localhost:" + wiremockPort);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod,
            HttpHeaders headers) {

        if (!headers.containsKey(HttpHeaders.ACCEPT)) {
            headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        }
        if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) {
            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        }

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort));

        HttpEntity<String> request = new HttpEntity<>(requestJson, headers);

        return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class);
    }

    public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) {
        return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders());
    }

    @Test
    public void executeCustomWorkflow() throws IOException {
        wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingWorkflow"))
                .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                        .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK)));

        wireMockServer.stubFor(get(urlMatching(
                ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be"))
                        .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                                .withBody(getWiremockResponseForCatalogdb("workflow_Response.json"))
                                .withStatus(org.apache.http.HttpStatus.SC_OK)));

        // expected response
        ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
        RequestReferences requestReferences = new RequestReferences();
        requestReferences.setInstanceId("1882939");
        requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d"));
        expectedResponse.setRequestReferences(requestReferences);
        uri = instanceManagementUri + "v1"
                + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be";
        ResponseEntity<String> response =
                sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers);

        assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value());
        ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class);
        assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId"));
    }
}