diff options
author | 2020-04-27 14:40:36 -0400 | |
---|---|---|
committer | 2020-04-27 21:53:38 -0400 | |
commit | 593187e78b52cada60430d4006900a3b50da170c (patch) | |
tree | d15e63f4e77f843b5bbafde6a9e325a55ac256f3 /mso-api-handlers/mso-api-handler-common/src/test/java/org/onap | |
parent | 0151f5c120f7d325a337efd522f7b46b0f027a1f (diff) |
refactor camunda client in apih
Switched CamundaClient to use restTemplate
Combined clients into one CamundaClient
Initial setup of exception handling in camundaclient
Initial fix of compilation issues
Switched CamundaClient constructor
Updated how url is set in CamundaClient
Updated auth to fix tag mismatch warning
Added throwing ClientConnectionException to client
Updated ServiceInstancesTest cases
Updated error handling for CamundaClient
Updated how response is returned
Fixed failing unit tests in apih infra
Refactored response handler for responseentity
Fixed failing unit tests in apih
Removed old unit tests for client
Import cleanup for unneeded changes
Updated to use new CamundaClient
Updated CamundaClient and ResponseHandler tests
Removed unused RequestHandler
Issue-ID: SO-2834
Signed-off-by: Benjamin, Max (mb388a) <mb388a@att.com>
Change-Id: I82ff489c9c939a7e8ec0e48476daf7e45baa5f20
Diffstat (limited to 'mso-api-handlers/mso-api-handler-common/src/test/java/org/onap')
4 files changed, 125 insertions, 422 deletions
diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java index 94c62a9689..e51f0e2412 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaClientTest.java @@ -24,109 +24,61 @@ package org.onap.so.apihandler.common; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolVersion; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; -import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.mockito.ArgumentCaptor; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; import org.skyscreamer.jsonassert.JSONAssert; -import org.springframework.mock.env.MockEnvironment; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.JsonMappingException; - -/** - * This class implements test methods of Camunda Beans. - * - * - */ +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; + +@RunWith(MockitoJUnitRunner.class) public class CamundaClientTest { - - @Mock - private HttpClient mockHttpClient; - private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void tesCamundaPost() throws JsonGenerationException, JsonMappingException, IOException { - - - String responseBody = - "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - - HttpResponse mockResponse = createResponse(200, responseBody); - mockHttpClient = Mockito.mock(HttpClient.class); - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(mockResponse); - - String reqXML = "<xml>test</xml>"; - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - MockEnvironment environment = new MockEnvironment(); - - environment.setProperty("mso.camundaUR", "yourValue1"); - environment.setProperty("mso.camundaAuth", - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE"); - environment.setProperty("org.onap.so.adapters.network.encryptionKey", "aa3871669d893c7fb8abbcda31b88b4f"); - - - RequestClientFactory reqClientFactory = new RequestClientFactory(); - reqClientFactory.setEnv(environment); - RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationURI); - - requestClient.setClient(mockHttpClient); - HttpResponse response = requestClient.post(reqXML, "reqId", "timeout", "version", null, null); + private RestTemplate restTemplate; + @Mock + private Environment env; - int statusCode = response.getStatusLine().getStatusCode(); - assertEquals(requestClient.getType(), CommonConstants.CAMUNDA); - assertEquals(statusCode, HttpStatus.SC_OK); + @Spy + private ResponseHandler responseHandler; + @Spy + @InjectMocks + private CamundaClient client; - requestClient = reqClientFactory.getRequestClient(orchestrationURI); - requestClient.setClient(mockHttpClient); - response = requestClient.post(null, "reqId", null, null, null, null); - assertEquals(requestClient.getType(), CommonConstants.CAMUNDA); - assertEquals(statusCode, HttpStatus.SC_OK); - verify(mockHttpClient, times(2)).execute(httpPostCaptor.capture()); - assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); - private HttpResponse createResponse(int respStatus, String respBody) { - HttpResponse response = - new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, "")); - response.setStatusCode(respStatus); - try { - response.setEntity(new StringEntity(respBody)); - response.setHeader("Content-Type", "application/json"); - } catch (Exception e) { - e.printStackTrace(); - } - return response; + @Before + public void setup() { + when(env.getRequiredProperty("mso.camundaAuth")) + .thenReturn("015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"); + when(env.getRequiredProperty("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); + when(env.getRequiredProperty("mso.camundaURL")).thenReturn("http://localhost:8080"); } public String inputStream(String JsonInput) throws IOException { @@ -136,10 +88,37 @@ public class CamundaClientTest { } @Test - public void wrapVIDRequestTest() throws IOException { - CamundaClient testClient = new CamundaClient(); - testClient.setUrl("/mso/async/services/CreateGenericALaCarteServiceInstance"); + public void createBPMNFailureExceptionNoResponseBodyTest() { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.NOT_IMPLEMENTED.value(), ex.getHttpResponseCode()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND", ex.getMessage()); + } + + @Test + public void createBPMNFailureExceptionWithCamundaResponseTest() throws IOException { + HttpClientErrorException e = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, + inputStream("/CamundaFailure.json").getBytes(), null); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.BAD_GATEWAY.value(), ex.getHttpResponseCode()); + assertEquals( + "Request Failed due to BPEL error with HTTP Status = 500 INTERNAL_SERVER_ERROR <aetgt:WorkflowException xmlns:aetgt=\"http://org.onap/so/workflow/schema/v1\"><aetgt:ErrorMessage>Exception in create execution list 500 </aetgt:ErrorMessage><aetgt:ErrorCode>7000</aetgt:ErrorCode></aetgt:WorkflowException>", + ex.getMessage()); + } + + @Test + public void createBPMNFailureExceptionTest() throws IOException { + String response = "Request failed"; + HttpClientErrorException e = + new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, response.getBytes(), null); + BPMNFailureException ex = client.createBPMNFailureException(e); + assertEquals(HttpStatus.BAD_GATEWAY.value(), ex.getHttpResponseCode()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 500 INTERNAL_SERVER_ERROR Request failed", + ex.getMessage()); + } + @Test + public void wrapVIDRequestTest() throws IOException { String requestId = "f7ce78bb-423b-11e7-93f8-0050569a796"; boolean isBaseVfModule = true; int recipeTimeout = 10000; @@ -161,7 +140,7 @@ public class CamundaClientTest { String requestUri = "v7/serviceInstances/assign"; String instanceGroupId = "ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - String testResult = testClient.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, + String testResult = client.wrapVIDRequest(requestId, isBaseVfModule, recipeTimeout, requestAction, serviceInstanceId, pnfCorrelationId, vnfId, vfModuleId, volumeGroupId, networkId, configurationId, serviceType, vnfType, vfModuleType, networkType, requestDetails, apiVersion, aLaCarte, requestUri, "", instanceGroupId, false); @@ -171,39 +150,43 @@ public class CamundaClientTest { } @Test - public void testPost() throws Exception { - CamundaClient testClient = new CamundaClient(); - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - MockEnvironment environment = new MockEnvironment(); - - environment.setProperty("mso.camundaUR", "yourValue1"); - testClient.setProps(environment); - testClient.setClient(mockHttpClient); - - testClient.setUrl(orchestrationURI); - - String responseBody = - "{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - assertNull(testClient.post(responseBody)); - + public void getClientConnectionExceptionTest() throws ApiException { + doThrow(ResourceAccessException.class).when(restTemplate).exchange(eq("http://localhost:8080/path"), + eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class)); + thrown.expect(ClientConnectionException.class); + thrown.expectMessage("Client from http://localhost:8080/path failed to connect or respond"); + client.get("/path"); } @Test - public void testPostWithRequestClientParameter() throws Exception { - CamundaClient testClient = new CamundaClient(); - String orchestrationURI = "/engine-rest/process-definition/key/dummy/start"; - HttpResponse mockResponse = createResponse(200, "{}"); - mockHttpClient = Mockito.mock(HttpClient.class); - Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(mockResponse); - - testClient.setClient(mockHttpClient); - testClient.setUrl(orchestrationURI); - - HttpResponse response = testClient.post(new RequestClientParameter.Builder().build()); - - assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + public void postClientConnectionExceptionTest() throws ApiException, IOException { + String jsonReq = inputStream("/WrappedVIDRequest.json"); + doThrow(ResourceAccessException.class).when(restTemplate).postForEntity(eq("http://localhost:8080/path"), + any(HttpEntity.class), eq(String.class)); + thrown.expect(ClientConnectionException.class); + thrown.expectMessage("Client from http://localhost:8080/path failed to connect or respond"); + client.post(jsonReq, "/path"); + } + @Test + public void getHttpStatusCodeExceptionTest() throws ApiException { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + doThrow(e).when(restTemplate).exchange(eq("http://localhost:8080/path"), eq(HttpMethod.GET), + any(HttpEntity.class), eq(String.class)); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND"); + client.get("/path"); } + @Test + public void postHttpStatusCodeExceptionTest() throws ApiException, IOException { + HttpServerErrorException e = new HttpServerErrorException(HttpStatus.NOT_FOUND); + String jsonReq = inputStream("/WrappedVIDRequest.json"); + doThrow(e).when(restTemplate).postForEntity(eq("http://localhost:8080/path"), any(HttpEntity.class), + eq(String.class)); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 404 NOT_FOUND"); + client.post(jsonReq, "/path"); + } } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java deleted file mode 100644 index 9e9ab6048e..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/CamundaTaskClientTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/*- - * ============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.apihandler.common; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import org.apache.http.HttpEntity; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpRequestBase; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.env.Environment; - -@RunWith(MockitoJUnitRunner.class) -public class CamundaTaskClientTest { - - @Mock - private Environment env; - private CamundaTaskClient testedObject = new CamundaTaskClient(); - private HttpClient httpClientMock; - private static final String JSON_REQUEST = "{\"value1\": \"aaa\",\"value2\": \"bbb\"}"; - private static final String URL_SCHEMA = "http"; - private static final String HOST = "testhost"; - private static final int PORT = 1234; - private static final String URL_PATH = "/requestMethodSuccessful"; - private static final String URL = URL_SCHEMA + "://" + HOST + ":" + PORT + URL_PATH; - private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; - - @Before - public void init() { - when(env.getProperty(eq(CommonConstants.CAMUNDA_AUTH))).thenReturn( - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE"); - when(env.getProperty(eq(CommonConstants.ENCRYPTION_KEY_PROP))).thenReturn("aa3871669d893c7fb8abbcda31b88b4f"); - testedObject = new CamundaTaskClient(); - httpClientMock = mock(HttpClient.class); - testedObject.setClient(httpClientMock); - testedObject.setUrl(URL); - } - - @Test - public void postMethodSuccessful() throws IOException { - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - testedObject.post(JSON_REQUEST); - verify(httpClientMock).execute(httpPostCaptor.capture()); - checkUri(httpPostCaptor.getValue()); - assertThat(httpPostCaptor.getValue().getEntity().getContentType().getValue()) - .isEqualTo(CommonConstants.CONTENT_TYPE_JSON); - assertThat(getJsonFromEntity(httpPostCaptor.getValue().getEntity())).isEqualTo(JSON_REQUEST); - } - - @Test - public void postMethodSuccessfulWithCredentials() throws IOException { - ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); - testedObject.setProps(env); - testedObject.post(JSON_REQUEST); - verify(httpClientMock).execute(httpPostCaptor.capture()); - assertThat(httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpPostCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } - - @Test - public void getMethodSuccessful() throws IOException { - ArgumentCaptor<HttpGet> httpGetCaptor = ArgumentCaptor.forClass(HttpGet.class); - testedObject.get(); - verify(httpClientMock).execute(httpGetCaptor.capture()); - checkUri(httpGetCaptor.getValue()); - } - - @Test - public void getMethodSuccessfulWithCredentials() throws IOException { - ArgumentCaptor<HttpGet> httpGetCaptor = ArgumentCaptor.forClass(HttpGet.class); - testedObject.setUrl(URL); - testedObject.setProps(env); - testedObject.get(); - verify(httpClientMock).execute(httpGetCaptor.capture()); - assertThat(httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)).isNotEmpty(); - Assert.assertEquals("Basic YXBpaEJwbW46Y2FtdW5kYS1SMTUxMiE=", - httpGetCaptor.getValue().getHeaders(AUTHORIZATION_HEADER_NAME)[0].getValue()); - } - - @Test(expected = UnsupportedOperationException.class) - public void postMethodUnsupported() { - testedObject.post("", "", "", "", "", ""); - } - - @Test(expected = UnsupportedOperationException.class) - public void postMethodUnsupported2() { - testedObject.post(new RequestClientParameter.Builder().build()); - } - - private void checkUri(HttpRequestBase httpRequestBase) { - assertThat(httpRequestBase.getURI().getScheme()).isEqualTo(URL_SCHEMA); - assertThat(httpRequestBase.getURI().getHost()).isEqualTo(HOST); - assertThat(httpRequestBase.getURI().getPort()).isEqualTo(PORT); - assertThat(httpRequestBase.getURI().getPath()).isEqualTo(URL_PATH); - } - - private String getJsonFromEntity(HttpEntity httpEntity) throws IOException { - BufferedReader rd = new BufferedReader(new InputStreamReader(httpEntity.getContent())); - StringBuilder result = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - result.append(line); - } - return result.toString(); - } - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java deleted file mode 100644 index 86b12ae8f6..0000000000 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/RequestClientTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (c) 2019 Samsung. 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.apihandler.common; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class RequestClientTest { - - private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; - - private RequestClient requestClient; - - @Before - public void init() { - requestClient = Mockito.mock(RequestClient.class, Mockito.CALLS_REAL_METHODS); - } - - @Test - public void getEncryptedPropValueWithSuccess() { - - String encryptedValue = requestClient.getEncryptedPropValue( - "E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE", - "defaultValue", ENCRYPTION_KEY); - - Assert.assertEquals("apihBpmn:camunda-R1512!", encryptedValue); - } - - @Test - public void getDefaultEncryptedPropValue() { - - String encryptedValue = - requestClient.getEncryptedPropValue("012345678901234567890123456789", "defaultValue", ENCRYPTION_KEY); - - Assert.assertEquals("defaultValue", encryptedValue); - } - -} diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java index 2095a9117d..e6f7a3663a 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/common/ResponseHandlerTest.java @@ -23,122 +23,42 @@ package org.onap.so.apihandler.common; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolVersion; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; -import org.apache.http.message.BasicStatusLine; +import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.ValidateException; - -/** - * This class implements test methods of CamundaResoponseHandler. - * - * - */ +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.springframework.http.ResponseEntity; + +@RunWith(MockitoJUnitRunner.class) public class ResponseHandlerTest { + @Spy + @InjectMocks + private ResponseHandler responseHandler; + @Rule public ExpectedException thrown = ExpectedException.none(); @Test - public void tesParseCamundaResponse() throws ApiException { - // String body - // ="{\"links\":[{\"method\":\"GET\",\"href\":\"http://localhost:9080/engine-rest/process-instance/2047c658-37ae-11e5-9505-7a1020524153\",\"rel\":\"self\"}],\"id\":\"2047c658-37ae-11e5-9505-7a1020524153\",\"definitionId\":\"dummy:10:73298961-37ad-11e5-9505-7a1020524153\",\"businessKey\":null,\"caseInstanceId\":null,\"ended\":true,\"suspended\":false}"; - - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200," - + "\"message\": \"Successfully started the process\"}"; - - HttpResponse response = createResponse(200, body, "application/json"); - - ResponseHandler respHandler = new ResponseHandler(response, 1); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertEquals(respHandler.getResponse().getMessage(), "Successfully started the process"); - - } - - @Test - public void tesParseCamundaResponseForCamundaTaskType() throws ApiException { - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 200," - + "\"message\": \"Successfully started the process\"}"; - - HttpResponse response = createResponse(200, body, "application/json"); - - ResponseHandler respHandler = new ResponseHandler(response, 2); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertEquals(respHandler.getResponseBody(), body); - - } - - @Test - public void tesParseBpelResponse() throws ApiException { - String body = "<test:service-response xmlns:test=\"http://org.onap/so/test\">" - + "<test:request-id>req5</test:request-id>" + "<test:request-action>test</test:request-action>" - + "<test:source>test</test:source>" + "<test:ack-final-indicator>n</test:ack-final-indicator>" - + "</test:service-response>"; - - HttpResponse response = createResponse(200, body, "text/xml"); - - ResponseHandler respHandler = new ResponseHandler(response, 0); - - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_ACCEPTED); - assertTrue(respHandler.getResponseBody() != null); - } - - @Test - public void tesMappingErrorResponse() throws ApiException { - thrown.expect(ValidateException.class); - thrown.expectMessage(startsWith("Cannot parse Camunda Response")); - thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); - thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - - HttpResponse response = createResponse(HttpStatus.SC_NOT_FOUND, "<html>error</html>", "text/html"); - ResponseHandler respHandler = new ResponseHandler(response, 1); - - int status = respHandler.getStatus(); - - assertEquals(HttpStatus.SC_NOT_IMPLEMENTED, status); - + public void acceptedResponseTest() throws IOException, BPMNFailureException { + ResponseEntity<String> camundaResponse = ResponseEntity.noContent().build(); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 204"); + responseHandler.acceptedResponse(camundaResponse); } @Test - public void tesGenricErrorResponse() throws ApiException { - - String body = "{ \"response\": \"<xml>xml</xml>\"," + "\"messageCode\": 500," - + "\"message\": \"Something went wrong\"}"; - - HttpResponse response = createResponse(500, body, "application/json"); - ResponseHandler respHandler = new ResponseHandler(response, 1); - int status = respHandler.getStatus(); - assertEquals(status, HttpStatus.SC_BAD_GATEWAY); - assertEquals(respHandler.getResponse().getMessage(), "Something went wrong"); - } + public void acceptedOrNoContentResponseTest() throws IOException, BPMNFailureException { + ResponseEntity<String> camundaResponse = ResponseEntity.badRequest().build(); + thrown.expect(BPMNFailureException.class); + thrown.expectMessage("Request Failed due to BPEL error with HTTP Status = 400"); + responseHandler.acceptedOrNoContentResponse(camundaResponse); - private HttpResponse createResponse(int respStatus, String respBody, String contentType) { - HttpResponse response = - new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), respStatus, "")); - response.setStatusCode(respStatus); - try { - response.setEntity(new StringEntity(respBody)); - response.setHeader("Content-Type", contentType); - } catch (Exception e) { - e.printStackTrace(); - } - return response; } } |