Add unit tests for ExternalAPIUtil
[so.git] / bpmn / MSOCommonBPMN / src / test / groovy / org / onap / so / bpmn / common / scripts / ExternalAPIUtilTest.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Nokia.
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 package org.onap.so.bpmn.common.scripts
21
22 import org.assertj.core.api.AbstractAssert
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.junit.Test
26 import org.onap.logging.ref.slf4j.ONAPLogConstants
27 import org.onap.so.client.HttpClient
28 import org.onap.so.client.HttpClientFactory
29 import org.onap.so.utils.TargetEntity
30 import org.springframework.http.HttpStatus
31
32 import javax.ws.rs.core.MediaType
33 import javax.ws.rs.core.Response
34
35 import static org.assertj.core.api.Assertions.assertThat
36 import static org.assertj.core.api.Assertions.catchThrowableOfType
37 import static org.mockito.BDDMockito.given
38 import static org.mockito.BDDMockito.then
39 import static org.mockito.BDDMockito.willThrow
40 import static org.mockito.Mockito.mock
41 import static org.mockito.Mockito.times
42
43 class ExternalAPIUtilTest {
44
45     private static final String URL = "http://someUrl"
46     private static final String UUID_STR = UUID.nameUUIDFromBytes("deterministic_uuid".getBytes())
47     private static final String BODY_PAYLOAD = "payload"
48
49     @Test
50     void executeExternalAPIGetCall_shouldPerformRestGetCall_withAuthorizationHeaderSet() {
51         // GIVEN
52         Response expectedResponse = createExpectedResponse(HttpStatus.ACCEPTED, BODY_PAYLOAD)
53         HttpClient httpClient = mock(HttpClient.class)
54         given(httpClient.get()).willReturn(expectedResponse)
55         HttpClientFactory httpClientFactory = mock(HttpClientFactory.class)
56         given(httpClientFactory.create(new URL(URL), MediaType.APPLICATION_JSON, TargetEntity.EXTERNAL)).willReturn(httpClient)
57
58         // WHEN
59         ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(httpClientFactory, new DummyMsoUtils(UUID_STR), new ExceptionUtil())
60         Response apiResponse = externalAPIUtil.executeExternalAPIGetCall(createDelegateExecution(), URL)
61
62         // THEN
63         then(httpClient).should(times(1)).addBasicAuthHeader("value_externalapi_auth", "value_mso_msoKey")
64         then(httpClient).should(times(1)).addAdditionalHeader("X-FromAppId", "MSO")
65         then(httpClient).should(times(1)).addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, UUID_STR)
66         then(httpClient).should(times(1)).addAdditionalHeader("Accept", MediaType.APPLICATION_JSON)
67         ResponseAssert.assertThat(apiResponse)
68                 .hasStatusCode(HttpStatus.ACCEPTED)
69                 .hasBody(BODY_PAYLOAD)
70     }
71
72     @Test
73     void executeExternalAPIGetCall_shouldHandleExceptionsThrownByGetCall_andRethrowAsBpmnError() {
74         // GIVEN
75         HttpClient httpClient = mock(HttpClient.class)
76         willThrow(new RuntimeException("error occurred")).given(httpClient).get()
77         HttpClientFactory httpClientFactory = mock(HttpClientFactory.class)
78         given(httpClientFactory.create(new URL(URL), MediaType.APPLICATION_JSON, TargetEntity.EXTERNAL)).willReturn(httpClient)
79         DelegateExecution delegateExecution = createDelegateExecution()
80         DummyExceptionUtil exceptionUtil = new DummyExceptionUtil()
81
82         // WHEN
83         ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(httpClientFactory, new DummyMsoUtils(UUID_STR), exceptionUtil)
84         BpmnError bpmnError = catchThrowableOfType({ -> externalAPIUtil.executeExternalAPIGetCall(delegateExecution, URL)
85         }, BpmnError.class)
86
87         // THEN
88         assertThat(exceptionUtil.getDelegateExecution()).isSameAs(delegateExecution)
89         assertThat(bpmnError.getMessage()).isEqualTo("error occurred")
90         assertThat(bpmnError.getErrorCode()).isEqualTo("9999")
91     }
92
93     @Test
94     void executeExternalAPIPostCall_shouldHandleExceptionsThrownByPostCall_andRethrowAsBpmnError() {
95         // GIVEN
96         HttpClient httpClient = mock(HttpClient.class)
97         willThrow(new RuntimeException("error occurred")).given(httpClient).post(BODY_PAYLOAD)
98         HttpClientFactory httpClientFactory = mock(HttpClientFactory.class)
99         given(httpClientFactory.create(new URL(URL), MediaType.APPLICATION_JSON, TargetEntity.AAI)).willReturn(httpClient)
100         DelegateExecution delegateExecution = createDelegateExecution()
101         DummyExceptionUtil exceptionUtil = new DummyExceptionUtil()
102
103         // WHEN
104         ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(httpClientFactory, new DummyMsoUtils(UUID_STR), exceptionUtil)
105         BpmnError bpmnError = catchThrowableOfType({ ->
106             externalAPIUtil.executeExternalAPIPostCall(delegateExecution, URL, BODY_PAYLOAD)
107         }, BpmnError.class)
108
109         // THEN
110         assertThat(exceptionUtil.getDelegateExecution()).isSameAs(delegateExecution)
111         assertThat(bpmnError.getMessage()).isEqualTo("error occurred")
112         assertThat(bpmnError.getErrorCode()).isEqualTo("9999")
113     }
114
115     @Test
116     void executeExternalAPIPostCall_shouldPerformRestPostCall_withPayloadAndAuthorizationHeaderSet() {
117         // GIVEN
118         Response expectedResponse = createExpectedResponse(HttpStatus.ACCEPTED, BODY_PAYLOAD)
119         HttpClient httpClient = mock(HttpClient.class)
120         given(httpClient.post(BODY_PAYLOAD)).willReturn(expectedResponse)
121         HttpClientFactory httpClientFactory = mock(HttpClientFactory.class)
122         given(httpClientFactory.create(new URL(URL), MediaType.APPLICATION_JSON, TargetEntity.AAI)).willReturn(httpClient)
123
124         // WHEN
125         ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(httpClientFactory, new DummyMsoUtils(UUID_STR), new ExceptionUtil())
126         Response apiResponse = externalAPIUtil.executeExternalAPIPostCall(createDelegateExecution(), URL, BODY_PAYLOAD)
127
128         // THEN
129         then(httpClient).should(times(1)).addBasicAuthHeader("value_externalapi_auth", "value_mso_msoKey")
130         then(httpClient).should(times(1)).addAdditionalHeader("X-FromAppId", "MSO")
131         then(httpClient).should(times(1)).addAdditionalHeader("X-TransactionId", UUID_STR)
132         ResponseAssert.assertThat(apiResponse)
133                 .hasStatusCode(HttpStatus.ACCEPTED)
134                 .hasBody(BODY_PAYLOAD)
135     }
136
137     private Response createExpectedResponse(HttpStatus httpStatus, String body) {
138         Response expectedResponse = mock(Response.class)
139         given(expectedResponse.getStatus()).willReturn(httpStatus.value())
140         given(expectedResponse.getEntity()).willReturn(body)
141         return expectedResponse
142     }
143
144     private DelegateExecution createDelegateExecution() {
145         DelegateExecution delegateExecution = mock(DelegateExecution.class)
146         given(delegateExecution.getVariable("URN_externalapi_auth")).willReturn("value_externalapi_auth")
147         given(delegateExecution.getVariable("URN_mso_msoKey")).willReturn("value_mso_msoKey")
148         return delegateExecution
149     }
150
151     private static class ResponseAssert extends AbstractAssert<ResponseAssert, Response> {
152
153         ResponseAssert(Response response) {
154             super(response, ResponseAssert.class)
155         }
156
157         static ResponseAssert assertThat(Response response) {
158             return new ResponseAssert(response)
159         }
160
161         ResponseAssert hasStatusCode(HttpStatus httpStatus) {
162             assertThat(actual.getStatus()).isEqualTo(httpStatus.value())
163             return this
164         }
165
166         ResponseAssert hasBody(String responseBody) {
167             assertThat(actual.getEntity()).isEqualTo(responseBody)
168             return this
169         }
170     }
171
172     private static class DummyMsoUtils extends MsoUtils {
173
174         private final String uuid
175
176         DummyMsoUtils(String uuid) {
177             this.uuid = uuid
178         }
179
180         String getRequestID() {
181             return uuid
182         }
183     }
184
185     private static class DummyExceptionUtil extends ExceptionUtil {
186
187         private DelegateExecution delegateExecution
188
189         @Override
190         void buildAndThrowWorkflowException(DelegateExecution delegateExecution, int errorCode, String errorMessage) {
191             this.delegateExecution = delegateExecution
192             throw new BpmnError(String.valueOf(errorCode), errorMessage)
193         }
194
195         DelegateExecution getDelegateExecution() {
196             return delegateExecution
197         }
198     }
199 }