diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:14:34 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2019-04-08 14:24:59 -0400 |
commit | f47919f1fe367b612fa9c96d34c59f01a541e882 (patch) | |
tree | 5b6aa2fc36747d868897e68ccbec0c6db0aee81c /mso-api-handlers/mso-api-handler-infra/src/test/java/org | |
parent | 54452b80a1cf4d22ef750bc1377f8c1b05431d57 (diff) |
Replaced all tabs with spaces in java and pom.xml
Added in maven plugins to enforce coding style rules
Added in eclipse java formatting xml
Change-Id: I3727bbf4ce8dc66abfd8ad21b6cfd0890c5d3ff0
Issue-ID: SO-1765
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra/src/test/java/org')
53 files changed, 6091 insertions, 5323 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java index 8a45752949..b8a2f22566 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandler.common; import static org.junit.Assert.assertEquals; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; @@ -33,41 +31,41 @@ import org.springframework.beans.factory.annotation.Autowired; public class ResponseBuilderTest extends BaseTest { - @Autowired - private ResponseBuilder builder; - + @Autowired + private ResponseBuilder builder; + @Test - public void testBuildResponseResponse () throws ApiException { - - String requestId = null; - String apiVersion = "1"; - String jsonResponse = "Successfully started the process"; - + public void testBuildResponseResponse() throws ApiException { + + String requestId = null; + String apiVersion = "1"; + String jsonResponse = "Successfully started the process"; + Response response = builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, jsonResponse, apiVersion); - + assertEquals(202, response.getStatus()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - + } - + @Test - public void testBuildResponseVersion () throws ApiException { - - String requestId = "123456-67889"; - String apiVersion = "v5"; - String jsonResponse = "Successfully started the process"; - + public void testBuildResponseVersion() throws ApiException { + + String requestId = "123456-67889"; + String apiVersion = "v5"; + String jsonResponse = "Successfully started the process"; + Response response = builder.buildResponse(HttpStatus.SC_CREATED, requestId, jsonResponse, apiVersion); - + assertEquals(201, response.getStatus()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - + } - + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java index db3dcb5af5..276b438529 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java @@ -23,35 +23,33 @@ package org.onap.so.apihandler.filters; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.IOException; import java.net.URI; - import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.UriInfo; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class RequestUriFilterTest extends BaseTest{ - - @Test - public void filterTest() throws IOException { - RequestUriFilter URIFilter = new RequestUriFilter(); - URI baseURI = URI.create("http://localhost:58879/"); - String requestURI = "onap/so/infra/serviceInstances/v5"; - - ContainerRequestContext mockContext = mock(ContainerRequestContext.class); - UriInfo mockInfo = mock(UriInfo.class); - - when(mockContext.getUriInfo()).thenReturn(mockInfo); - when(mockInfo.getBaseUri()).thenReturn(baseURI); - when(mockInfo.getPath()).thenReturn(requestURI); - - - URIFilter.filter(mockContext); - assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances", URIFilter.getRequestUri()); - } +public class RequestUriFilterTest extends BaseTest { + + @Test + public void filterTest() throws IOException { + RequestUriFilter URIFilter = new RequestUriFilter(); + URI baseURI = URI.create("http://localhost:58879/"); + String requestURI = "onap/so/infra/serviceInstances/v5"; + + ContainerRequestContext mockContext = mock(ContainerRequestContext.class); + UriInfo mockInfo = mock(UriInfo.class); + + when(mockContext.getUriInfo()).thenReturn(mockInfo); + when(mockInfo.getBaseUri()).thenReturn(baseURI); + when(mockInfo.getPath()).thenReturn(requestURI); + + + URIFilter.filter(mockContext); + assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances", + URIFilter.getRequestUri()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java index 564121b7b5..9065a1a9ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java @@ -1,30 +1,23 @@ /* - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP - SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.recipe; import static org.junit.Assert.assertEquals; - import java.io.ByteArrayInputStream; import java.io.IOException; - import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.junit.Before; @@ -32,41 +25,41 @@ import org.junit.Test; import org.mockito.Mockito; public class CamundaClientErrorHandlerTest { - - private ClientHttpResponse clientHttpResponse; - private CamundaClientErrorHandler clientErrorHandler; - - @Before - public void before() { - clientHttpResponse = Mockito.mock(ClientHttpResponse.class); - clientErrorHandler = new CamundaClientErrorHandler(); - } - - @Test - public void handleError_SERVER_ERROR_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(true, serverHasError); - } - - @Test - public void handleError_CLIENT_ERROR_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(true, clientHasError); - } - - @Test - public void handleError_SUCCESS_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(false, hasNoError); - } - -}
\ No newline at end of file + + private ClientHttpResponse clientHttpResponse; + private CamundaClientErrorHandler clientErrorHandler; + + @Before + public void before() { + clientHttpResponse = Mockito.mock(ClientHttpResponse.class); + clientErrorHandler = new CamundaClientErrorHandler(); + } + + @Test + public void handleError_SERVER_ERROR_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(true, serverHasError); + } + + @Test + public void handleError_CLIENT_ERROR_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(true, clientHasError); + } + + @Test + public void handleError_SUCCESS_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(false, hasNoError); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java index 68869b77d4..75a6eeea7d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java @@ -19,14 +19,14 @@ */ package org.onap.so.apihandlerinfra; -import org.junit.runner.RunWith; +import org.junit.runner.RunWith; import com.googlecode.junittoolbox.SuiteClasses; import com.googlecode.junittoolbox.WildcardPatternSuite; @RunWith(WildcardPatternSuite.class) @SuiteClasses("**/*Test.class") public class AllTestsTestSuite { - // the class remains empty, - // used only as a holder for the above annotations + // the class remains empty, + // used only as a holder for the above annotations } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java index 6efcdc47e5..bc867503f2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java @@ -26,15 +26,12 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.exceptions.*; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import java.io.IOException; import java.util.LinkedList; import java.util.List; - import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; @@ -52,7 +49,8 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage("Message rewritten"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build(); + RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build(); throw testException; } @@ -65,8 +63,9 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage(startsWith("Request Failed due to BPEL error with HTTP Status =")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - thrown.expect(hasProperty("variables",sameBeanAs(testVariables))); - BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build(); + thrown.expect(hasProperty("variables", sameBeanAs(testVariables))); + BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build(); throw testException; } @@ -81,33 +80,40 @@ public class ApiExceptionTest extends BaseTest { thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); thrown.expect(hasProperty("cause", sameBeanAs(ioException))); - ClientConnectionException testException = new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).cause(ioException).build(); + ClientConnectionException testException = + new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER) + .cause(ioException).build(); throw testException; } @Test public void testDuplicateRequestException() throws ApiException { - ErrorLoggerInfo testLog = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ErrorLoggerInfo testLog = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); thrown.expect(DuplicateRequestException.class); thrown.expectMessage(startsWith("Error: Locked instance")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); thrown.expect(hasProperty("errorLoggerInfo", sameBeanAs(testLog))); - DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2","Test3","Test4", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build(); + DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2", "Test3", + "Test4", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build(); throw testException; } @Test public void testValidateException() throws ApiException { - + thrown.expect(ValidateException.class); thrown.expectMessage("Test Message"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); - ValidateException testException = new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); + ValidateException testException = + new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER) + .messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); throw testException; } @@ -118,7 +124,9 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage("Test Message"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_CONFLICT))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - VfModuleNotFoundException testException = new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build(); + VfModuleNotFoundException testException = + new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build(); throw testException; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java index 170b305bb5..da37be98b2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java @@ -24,9 +24,7 @@ package org.onap.so.apihandlerinfra; import java.nio.file.Files; import java.nio.file.Paths; - import javax.transaction.Transactional; - import org.junit.After; import org.junit.BeforeClass; import org.junit.runner.RunWith; @@ -41,7 +39,6 @@ import org.springframework.core.env.Environment; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; - import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; @@ -52,42 +49,46 @@ import com.github.tomakehurst.wiremock.client.WireMock; @Transactional @AutoConfigureWireMock(port = 0) public abstract class BaseTest { - protected Logger logger = LoggerFactory.getLogger(BaseTest.class); - protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + protected Logger logger = LoggerFactory.getLogger(BaseTest.class); + protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + @Autowired + protected Environment env; + + @LocalServerPort + private int port; + + @Autowired + protected WireMockServer wireMockServer; + + protected String createURLWithPort(String uri) { + return "http://localhost:" + port + uri; + } + + protected String createURLWithPort(String uri, int iPort) { + return "http://localhost:" + iPort + uri; + } - @Autowired - protected Environment env; + @After + public void tearDown() { + wireMockServer.resetAll(); + } - @LocalServerPort - private int port; - - @Autowired - protected WireMockServer wireMockServer; - - protected String createURLWithPort(String uri) { - return "http://localhost:" + port + uri; - } - - protected String createURLWithPort(String uri, int iPort) { - return "http://localhost:" + iPort + uri; - } - - @After - public void tearDown(){ - wireMockServer.resetAll(); - } + public static String getResponseTemplate; + public static String getResponseTemplateNoBody; + public static String infraActivePost; - public static String getResponseTemplate; - public static String getResponseTemplateNoBody; - public static String infraActivePost; - @BeforeClass - public static void setupTest() throws Exception { - getResponseTemplate = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json"))); - getResponseTemplateNoBody = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json"))); - infraActivePost = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json"))); - } + @BeforeClass + public static void setupTest() throws Exception { + getResponseTemplate = new String(Files + .readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json"))); + getResponseTemplateNoBody = new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json"))); + infraActivePost = new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json"))); + } - public String getTestUrl(String requestId) { - return "/infraActiveRequests/" + requestId; - } + public String getTestUrl(String requestId) { + return "/infraActiveRequests/" + requestId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java index e249c2d8ef..53982ca9d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java @@ -1,4 +1,5 @@ package org.onap.so.apihandlerinfra; + /*- * ============LICENSE_START======================================================= * ONAP - SO @@ -20,7 +21,6 @@ package org.onap.so.apihandlerinfra; */ import org.junit.Before; import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.PojoClassFilter; import com.openpojo.reflection.filters.FilterEnum; @@ -33,36 +33,34 @@ import com.openpojo.validation.test.impl.SetterTester; public class BeanMultiTest { - Validator validator; - PojoClassFilter enumFilter; - private PojoClassFilter filterTestClasses = new FilterTestClasses(); + Validator validator; + PojoClassFilter enumFilter; + private PojoClassFilter filterTestClasses = new FilterTestClasses(); + + @Before + public void setup() { + enumFilter = new FilterEnum(); + validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + } + + @Test + public void validateBeansMsoApihandlerBeans() { + test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans"); + test("org.onap.so.apihandlerinfra.tasksbeans"); + test("org.onap.so.apihandlerinfra.vnfbeans"); + test("org.onap.so.apihandlerinfra.tenantisolationbeans"); + test("org.onap.so.apihandlerinfra.workflowspecificationbeans"); + } - @Before - public void setup(){ - enumFilter = new FilterEnum(); - validator = ValidatorBuilder.create() - .with(new SetterMustExistRule(), - new GetterMustExistRule()) - .with(new SetterTester(), - new GetterTester()) - .build(); - } - @Test - public void validateBeansMsoApihandlerBeans() { - test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans"); - test("org.onap.so.apihandlerinfra.tasksbeans"); - test("org.onap.so.apihandlerinfra.vnfbeans"); - test("org.onap.so.apihandlerinfra.tenantisolationbeans"); - test("org.onap.so.apihandlerinfra.workflowspecificationbeans"); - } + private void test(String packageName) { + validator.validate(packageName, enumFilter, filterTestClasses); - private void test(String packageName) { - validator.validate(packageName, enumFilter, filterTestClasses); + } - } - private static class FilterTestClasses implements PojoClassFilter { - public boolean include(PojoClass pojoClass) { - return !pojoClass.getSourcePath().contains("/test-classes/"); - } - } + private static class FilterTestClasses implements PojoClassFilter { + public boolean include(PojoClass pojoClass) { + return !pojoClass.getSourcePath().contains("/test-classes/"); + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java index 18eb46278d..7ddab572e3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java @@ -29,14 +29,11 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; - import java.io.IOException; 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; @@ -50,224 +47,239 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; public class E2EServiceInstancesTest extends BaseTest { -private final ObjectMapper mapper = new ObjectMapper(); - - private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/"; - - - @Before - public void init() throws JsonProcessingException { - wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson("{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setServiceModelUUID(defaultService.getModelUUID()); - serviceRecipe.setAction(Action.scaleInstance.name()); - serviceRecipe.setRecipeTimeout(180); - serviceRecipe.setOrchestrationUri("/testOrchestrationUri"); - - wireMockServer.stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - } - public String inputStream(String JsonInput)throws IOException{ - JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput; - return new String(Files.readAllBytes(Paths.get(JsonInput))); - } - public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type",MediaType.APPLICATION_JSON); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath)); - HttpEntity<String> request = new HttpEntity<>(requestJson, headers); - - return restTemplate.exchange(builder.toUriString(), - reqMethod, request, String.class); - } - - @Test - public void createE2EServiceInstanceNoRequestInfo() throws IOException{ - String uri = e2eServInstancesUri + "v3"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void updateE2EServiceInstanceJSONMappingError() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void updateE2EServiceInstanceNoRequestorId() throws IOException{ - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC0002"); - exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); - } - @Test - public void deleteE2EServiceInstance() throws IOException{ - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC1000"); - exception.setText("No communication to catalog DB null"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void deleteE2EServiceInstanceNotValid() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void getE2EServiceInstanceNullOperationalStatus() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET); - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void scaleE2EServiceInstanceMappingError() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void scaleE2EServiceInstance() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; - ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void updateE2EServiceInstance() throws IOException{ - String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void getE2EServiceInstance() throws IOException{ - OperationStatus status = new OperationStatus(); - status.setOperationId("operationId"); - status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e"); - wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(status)) - .withStatus(HttpStatus.SC_OK))); - String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId"; - ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void compareModelWithTargetVersionBadRequest() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void compareModelWithTargetVersion() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("Camunda/SuccessfulResponse.json").withStatus(org.apache.http.HttpStatus.SC_ACCEPTED))); - - String expectedResponse = "success"; - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - String actualResponse = response.getBody(); - assertEquals(expectedResponse, actualResponse); - } - @Test - public void compareModelWithTargetVersionEmptyResponse() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); - - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC1000"); - exception.setText("Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); - } - @Test - public void compareModelWithTargetVersionBadBpelResponse() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status")); - } - @Test - public void compareModelWithTargetVersionNoBPELResponse() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody("{}").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status")); - } -}
\ No newline at end of file + private final ObjectMapper mapper = new ObjectMapper(); + + private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/"; + + + @Before + public void init() throws JsonProcessingException { + wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson( + "{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setServiceModelUUID(defaultService.getModelUUID()); + serviceRecipe.setAction(Action.scaleInstance.name()); + serviceRecipe.setRecipeTimeout(180); + serviceRecipe.setOrchestrationUri("/testOrchestrationUri"); + + wireMockServer.stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + } + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath)); + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class); + } + + @Test + public void createE2EServiceInstanceNoRequestInfo() throws IOException { + String uri = e2eServInstancesUri + "v3"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void updateE2EServiceInstanceJSONMappingError() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void updateE2EServiceInstanceNoRequestorId() throws IOException { + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC0002"); + exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); + } + + @Test + public void deleteE2EServiceInstance() throws IOException { + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC1000"); + exception.setText("No communication to catalog DB null"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void deleteE2EServiceInstanceNotValid() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void getE2EServiceInstanceNullOperationalStatus() throws IOException { + String uri = e2eServInstancesUri + + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET); + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void scaleE2EServiceInstanceMappingError() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void scaleE2EServiceInstance() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; + ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void updateE2EServiceInstance() throws IOException { + String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void getE2EServiceInstance() throws IOException { + OperationStatus status = new OperationStatus(); + status.setOperationId("operationId"); + status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e"); + wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(status)).withStatus(HttpStatus.SC_OK))); + String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId"; + ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void compareModelWithTargetVersionBadRequest() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void compareModelWithTargetVersion() throws IOException { + wireMockServer.stubFor( + post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn(aResponse() + .withHeader("Content-Type", "application/json").withBodyFile("Camunda/SuccessfulResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_ACCEPTED))); + + String expectedResponse = "success"; + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + String actualResponse = response.getBody(); + assertEquals(expectedResponse, actualResponse); + } + + @Test + public void compareModelWithTargetVersionEmptyResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) + .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); + + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC1000"); + exception.setText( + "Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); + } + + @Test + public void compareModelWithTargetVersionBadBpelResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/TestResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText() + .contains("Request Failed due to BPEL error with HTTP Status")); + } + + @Test + public void compareModelWithTargetVersionNoBPELResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{}") + .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText() + .contains("Request Failed due to BPEL error with HTTP Status")); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java index 1e4b99d4ff..5d0fb298d9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java @@ -19,10 +19,10 @@ */ package org.onap.so.apihandlerinfra; + import ch.vorburger.exec.ManagedProcessException; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.jdbc.DataSourceBuilder; @@ -36,17 +36,14 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; - import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @Profile({"test"}) @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "entityManagerFactory", - basePackages = {"org.onap.so.db.catalog.data.repository"} - ) +@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", + basePackages = {"org.onap.so.db.catalog.data.repository"}) public class EmbeddedCatalogDbConfig { @Bean @@ -54,49 +51,36 @@ public class EmbeddedCatalogDbConfig { return new MariaDB4jSpringService(); } - @Primary - @Bean(name = "dataSource") + @Primary + @Bean(name = "dataSource") DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, - @Value("${mariaDB4j.databaseName}") String databaseName, - @Value("${spring.datasource.username}") String datasourceUsername, - @Value("${spring.datasource.password}") String datasourcePassword, - @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { - //Create our database with default root user and no password + @Value("${mariaDB4j.databaseName}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + // Create our database with default root user and no password mariaDB4jSpringService.getDB().createDB(databaseName); DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); - return DataSourceBuilder - .create() - .username(datasourceUsername) - .password(datasourcePassword) - .url(config.getURL(databaseName)) - .driverClassName(datasourceDriver) - .build(); + return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword) + .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build(); } - - @Primary - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("dataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.catalog.beans") - .persistenceUnit("catalogDB") - .build(); - } - @Primary - @Bean(name = "transactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("entityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Primary + @Bean(name = "entityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("dataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB") + .build(); + } + + @Primary + @Bean(name = "transactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java index 00efb6b410..0ec06177c8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java @@ -19,10 +19,10 @@ */ package org.onap.so.apihandlerinfra; + import ch.vorburger.exec.ManagedProcessException; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.jdbc.DataSourceBuilder; @@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; - import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @Profile({"test"}) @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager", - basePackages = { "org.onap.so.db.request.data.repository" } - ) +@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory", + transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"}) public class EmbeddedRequestDbConfig { @Bean @@ -56,47 +53,34 @@ public class EmbeddedRequestDbConfig { } - @Bean(name = "requestDataSource") - @ConfigurationProperties(prefix = "request.datasource") + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "request.datasource") DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, - @Value("${mariaDB4j.databaseName2}") String databaseName, - @Value("${spring.datasource.username}") String datasourceUsername, - @Value("${spring.datasource.password}") String datasourcePassword, - @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { - //Create our database with default root user and no password + @Value("${mariaDB4j.databaseName2}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + // Create our database with default root user and no password mariaDB4jSpringService.getDB().createDB(databaseName); DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); - return DataSourceBuilder - .create() - .username(datasourceUsername) - .password(datasourcePassword) - .url(config.getURL(databaseName)) - .driverClassName(datasourceDriver) - .build(); + return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword) + .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build(); } - @Bean(name = "requestEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("requestDataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.request.beans") - .persistenceUnit("requestDB") - .build(); - } + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB") + .build(); + } - @Bean(name = "requestTransactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("requestEntityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java index 45fadb540a..928b488f6a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java @@ -25,18 +25,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; import java.net.URI; import java.util.Collections; import java.util.List; - import org.springframework.test.util.ReflectionTestUtils; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; - import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; @@ -62,175 +59,170 @@ public class GlobalHealthcheckHandlerTest { @Mock ContainerRequestContext requestContext; - + @InjectMocks @Spy - GlobalHealthcheckHandler globalhealth; - - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - + GlobalHealthcheckHandler globalhealth; + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Test + public void testQuerySubsystemHealthNullResult() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080"); + + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(null); + + String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN); + System.out.println(result); + assertEquals(HealthcheckStatus.DOWN.toString(), result); + } + + @Test + public void testQuerySubsystemHealthNotNullResult() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + subSystemResponse.setStatus("UP"); + ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r); + + String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC); + System.out.println(result); + assertEquals(HealthcheckStatus.UP.toString(), result); + } + + private Response globalHealthcheck(String status) { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); + ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); + ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); + + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + + subSystemResponse.setStatus(status); + ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r); + + Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890"); + Response response = globalhealth.globalHealthcheck(true, requestContext); + + return response; + } + + @Test + public void globalHealthcheckAllUPTest() throws JSONException { + Response response = globalHealthcheck("UP"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthcheckResponse root; + root = (HealthcheckResponse) response.getEntity(); + String apistatus = root.getApih(); + assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String bpmnstatus = root.getBpmn(); + assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String sdncstatus = root.getSdncAdapter(); + assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String asdcstatus = root.getAsdcController(); + assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String catastatus = root.getCatalogdbAdapter(); + assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String reqdbstatus = root.getRequestdbAdapter(); + assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String openstatus = root.getOpenstackAdapter(); + assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String reqdbattstatus = root.getRequestdbAdapterAttsvc(); + assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + } + + @Test + public void globalHealthcheckAllDOWNTest() throws JSONException { + Response response = globalHealthcheck("DOWN"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthcheckResponse root; + root = (HealthcheckResponse) response.getEntity(); + String apistatus = root.getApih(); + assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String bpmnstatus = root.getBpmn(); + assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String sdncstatus = root.getSdncAdapter(); + assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String asdcstatus = root.getAsdcController(); + assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String catastatus = root.getCatalogdbAdapter(); + assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String reqdbstatus = root.getRequestdbAdapter(); + assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String openstatus = root.getOpenstackAdapter(); + assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String reqdbattstatus = root.getRequestdbAdapterAttsvc(); + assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + } + @Test - public void testQuerySubsystemHealthNullResult(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080"); - - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(null); - - String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN); - System.out.println(result); - assertEquals(HealthcheckStatus.DOWN.toString(),result); + public void buildHttpEntityForRequestTest() { + HttpEntity<String> he = globalhealth.buildHttpEntityForRequest(); + assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getAccept().get(0)); + assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getContentType()); } - + @Test - public void testQuerySubsystemHealthNotNullResult(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - subSystemResponse.setStatus("UP"); - ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(r); - - String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC); - System.out.println(result); - assertEquals(HealthcheckStatus.UP.toString(),result); + public void getEndpointUrlForSubsystemEnumTest() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); + ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); + ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); + + String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC); + assertEquals("http://localhost:8080", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC); + assertEquals("http://localhost:8081", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN); + assertEquals("http://localhost:8082", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB); + assertEquals("http://localhost:8083", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK); + assertEquals("http://localhost:8084", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB); + assertEquals("http://localhost:8085", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT); + assertEquals("http://localhost:8086", result); } - - private Response globalHealthcheck (String status){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); - - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - - subSystemResponse.setStatus(status); - ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(r); - - Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890"); - Response response = globalhealth.globalHealthcheck(true, requestContext); - - return response; + + @Test + public void processResponseFromSubsystemTest() { + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + subSystemResponse.setStatus("UP"); + ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + String result = globalhealth.processResponseFromSubsystem(r, MsoSubsystems.BPMN); + assertEquals("UP", result); } - - @Test - public void globalHealthcheckAllUPTest() throws JSONException { - Response response = globalHealthcheck("UP"); - assertEquals(Response.Status.OK.getStatusCode(),response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - } - - @Test - public void globalHealthcheckAllDOWNTest() throws JSONException { - Response response = globalHealthcheck("DOWN"); - assertEquals(Response.Status.OK.getStatusCode(),response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - } - - @Test - public void buildHttpEntityForRequestTest(){ - HttpEntity<String> he = globalhealth.buildHttpEntityForRequest(); - assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getAccept().get(0)); - assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getContentType()); - } - - @Test - public void getEndpointUrlForSubsystemEnumTest(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); - - String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC); - assertEquals("http://localhost:8080", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC); - assertEquals("http://localhost:8081", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN); - assertEquals("http://localhost:8082", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB); - assertEquals("http://localhost:8083", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK); - assertEquals("http://localhost:8084", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB); - assertEquals("http://localhost:8085", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT); - assertEquals("http://localhost:8086", result); - } - - @Test - public void processResponseFromSubsystemTest(){ - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - subSystemResponse.setStatus("UP"); - ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - String result = globalhealth.processResponseFromSubsystem(r,MsoSubsystems.BPMN); - assertEquals("UP",result); - } - -}
\ No newline at end of file + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index e694120405..9fc9e4a51b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -32,17 +32,14 @@ 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; @@ -57,17 +54,16 @@ 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{ +public class InstanceManagementTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); - private final ObjectMapper mapper = new ObjectMapper(); - private ObjectMapper errorMapper = new ObjectMapper(); - @Value("${wiremock.server.port}") - private String wiremockPort; + private String wiremockPort; private final String instanceManagementUri = "/onap/so/infra/instanceManagement/"; @@ -77,99 +73,102 @@ public class InstanceManagementTest extends BaseTest{ 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); + @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 = 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{ + 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; + 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); - } + + 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); + 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()); + + 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")) + 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 + 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")); + 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); + 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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index a22e61e75f..ad0a878931 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java @@ -27,7 +27,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static org.onap.so.logger.MdcConstants.ECOMP_REQUEST_ID; import static org.onap.so.logger.MdcConstants.ENDTIME; @@ -38,13 +37,10 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; import static org.onap.so.logger.MdcConstants.CLIENT_ID; - import java.io.IOException; import java.util.Map; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -60,15 +56,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class ManualTasksTest extends BaseTest{ +public class ManualTasksTest extends BaseTest { private final String basePath = "/tasks/v1/"; @@ -83,14 +77,14 @@ public class ManualTasksTest extends BaseTest{ RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); reqInfo.setRequestorId("testId"); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); - //expected response + // expected response TaskRequestReference expectedResponse = new TaskRequestReference(); - expectedResponse.setTaskId(taskId); + expectedResponse.setTaskId(taskId); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -98,10 +92,10 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); @@ -111,32 +105,31 @@ public class ManualTasksTest extends BaseTest{ TaskRequestReference realResponse = mapper.readValue(response.getBody(), TaskRequestReference.class); - //then - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - assertThat(realResponse, sameBeanAs(expectedResponse)); - - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + // then + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + assertThat(realResponse, sameBeanAs(expectedResponse)); + + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS",mdc.get(STATUSCODE)); - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); + assertEquals("INPROGRESS", mdc.get(STATUSCODE)); + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ENDTIME)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202",mdc.get(RESPONSECODE)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE",mdc.get(STATUSCODE)); + assertEquals("202", mdc.get(RESPONSECODE)); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); + assertEquals("COMPLETE", mdc.get(STATUSCODE)); assertNotNull(mdc.get(RESPONSEDESC)); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); @@ -144,6 +137,7 @@ public class ManualTasksTest extends BaseTest{ assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); } } + @Test public void completeTaskMappingError() throws IOException { String invalidRequest = "test"; @@ -151,9 +145,9 @@ public class ManualTasksTest extends BaseTest{ ServiceException se = new ServiceException(); se.setMessageId("SVC0002"); se.setText("Mapping of request to JSON object failed: Unrecognized token \'test\': " - + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]"); + + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]"); expectedResponse.setServiceException(se); - + HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -161,26 +155,27 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<String> entity = new HttpEntity<String>(invalidRequest, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } + @Test public void completeTaskValidationError() throws IOException { String taskId = "55"; TasksRequest taskReq = new TasksRequest(); RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); @@ -197,30 +192,31 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } + @Test public void completeTaskBpelResponseError() throws IOException { - wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE))); + wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE))); String taskId = "55"; TasksRequest taskReq = new TasksRequest(); RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); reqInfo.setRequestorId("testId"); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); @@ -237,10 +233,10 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); @@ -248,7 +244,7 @@ public class ManualTasksTest extends BaseTest{ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index d6fff7bdfb..c30b9dedf2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.io.IOException; import java.io.StringReader; import java.net.URL; @@ -32,12 +31,10 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Optional; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; - import org.apache.http.HttpStatus; import org.junit.ClassRule; import org.junit.Rule; @@ -49,11 +46,9 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; - import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.w3c.dom.Document; @@ -61,463 +56,977 @@ import org.xml.sax.InputSource; @RunWith(JUnitParamsRunner.class) public class MsoRequestTest extends BaseTest { - private ObjectMapper mapper = new ObjectMapper(); - private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>(); - private ServiceInstancesRequest sir; - private MsoRequest msoRequest; - private Action action; - private String version; - private int reqVersion; - private String originalRequestJSON; - private String requestJSON; - private boolean expected; - private String expectedException; - - @ClassRule + private ObjectMapper mapper = new ObjectMapper(); + private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>(); + private ServiceInstancesRequest sir; + private MsoRequest msoRequest; + private Action action; + private String version; + private int reqVersion; + private String originalRequestJSON; + private String requestJSON; + private boolean expected; + private String expectedException; + + @ClassRule public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public String inputStream(String JsonInput)throws IOException{ - JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; - String input = new String(Files.readAllBytes(Paths.get(JsonInput))); - return input; - } - //Tests for successful validation of incoming JSON requests through the parse method - @Test - @Parameters(method = "successParameters") - public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{ - this.sir = sir; - this.instanceIdMapTest = instanceIdMapTest; - this.action = action; - this.reqVersion = reqVersion; - this.version = "v" + reqVersion; - this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Parameters - private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException{ - return Arrays.asList(new Object[][]{ - {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, - {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, - {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "3"}, - {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"}, - {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"}, - {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "6"}, - {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"} - }); - } - @Test - @Parameters(method = "customWorkflowSuccessParameters") - public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{ - this.sir = sir; - this.instanceIdMapTest = instanceIdMapTest; - this.action = action; - this.reqVersion = reqVersion; - this.version = "v" + reqVersion; - this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Parameters - private Collection<Object[]> customWorkflowSuccessParameters() throws JsonParseException, JsonMappingException, IOException{ - return Arrays.asList(new Object[][]{ - {mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"} - - }); - } - @Test - @Parameters(method = "aLaCarteParameters") - public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) throws JsonParseException, IOException, ValidationException{ - this.expected = expected; - this.sir = sir; - this.msoRequest = new MsoRequest(); - assertEquals(expected, msoRequest.getAlacarteFlag(sir)); - } - @Parameters - private Collection<Object[]> aLaCarteParameters() throws IOException{ - return Arrays.asList(new Object[][] { - {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class)}, - {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"), ServiceInstancesRequest.class)} - }); - } - //Tests various scenarios ensuring that requests containing missing or invalid information will throw a ValidationException - @Test - @Parameters(method = "validationParameters") - public void validationFailureTest(String expectedException, ServiceInstancesRequest sir, HashMap<String,String> instanceIdMapTest, Action action, int reqVersion) throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.expectedException = expectedException; - this.sir = sir; - this.instanceIdMapTest = instanceIdMapTest; - this.action = action; - this.reqVersion = reqVersion; - this.version = "v" + reqVersion; - this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - thrown.expect(ValidationException.class); - thrown.expectMessage(expectedException); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Parameters - private Collection<Object[]> validationParameters() throws IOException{ - return Arrays.asList(new Object[][] { - //ValidationException for CloudConfiguration - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateAndCloudDelete, 7}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - //ValidationException for ModelInfo - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 6}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 6}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid model-info is specified", mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId format is specified", mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 3}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 4}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelType is specified", mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 4}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - //ValidationException for Platform and LineOfBusiness - {"No valid lineOfBusinessName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid platform is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6}, - {"No valid platformName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - //ValidationException for Project and OwningEntity - {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6}, - {"No valid owningEntityId is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid projectName is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //ValidationException for RelatedInstances - {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid destination vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceName format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 6}, - {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 6}, - {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelInfo in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelName in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersion in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid related service instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related service instance for vnf request is specified", mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related service instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related vnf instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related vnf instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 6}, - {"No valid source vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid instanceName format is specified", mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2}, - {"No valid relatedInstanceList is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - {"No valid related service instance for instanceGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - //ValidationException for RequestInfo - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - //ValidationException for RequestParameters - {"No valid aLaCarte in requestParameters", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 4}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //ValidationException for SubscriberInfo - {"No valid globalSubscriberId is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriptionServiceType is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //Validation for UserParams - {"No valid cloudConfiguration in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid cloudConfiguration in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams service modelInfo is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid platform in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid platformName in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid productFamilyId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid vfModules in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModules.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams vfModules resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //Validation for ConfigurationParameters - {"No valid configuration parameters is specified", mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - //Validation for Add and Remove Members - {"No valid vnf relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid related instances is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid source is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid instanceId in relatedInstances is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeMembers, 7} - }); - } - @Test - public void nullInstanceIdMapTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest = null; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(NullPointerException.class); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - - @Test - public void serviceInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void vnfInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("vnfInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid vnfInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void vfModuleInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("vfModuleInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid vfModuleInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void volumeGroupInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("volumeGroupInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid volumeGroupInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void networkInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("networkInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid networkInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void configurationInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("configurationInstanceId", "test"); - this.action = Action.createInstance; - thrown.expect(ValidationException.class); - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expectMessage("No valid configurationInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void instanceGroupIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("instanceGroupInstanceId", "test"); - this.action = Action.createInstance; - thrown.expect(ValidationException.class); - this.reqVersion = 7; - this.version = "v" + reqVersion; - thrown.expectMessage("No valid instanceGroupInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void testVfModuleV4UsePreLoad() throws JsonParseException, JsonMappingException, IOException, ValidationException { - this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json"); - this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.reqVersion = 4; - this.version = "v" + reqVersion; - this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); - this.msoRequest = new MsoRequest (); - msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false); - - this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json"); - this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); - msoRequest = new MsoRequest (); - msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false); - } - @Test - public void buildServiceErrorResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Mapping of request to JSON object failed. ", - ErrorNumbers.SVC_BAD_PARAMETER, null, version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; + String input = new String(Files.readAllBytes(Paths.get(JsonInput))); + return input; + } + + // Tests for successful validation of incoming JSON requests through the parse method + @Test + @Parameters(method = "successParameters") + public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, + int reqVersion) throws ValidationException, IOException { + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException { + return Arrays.asList(new Object[][] { + {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, + {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, + {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, "3"}, + {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"}, + {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"}, + {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, "6"}, + {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}}); + } + + @Test + @Parameters(method = "customWorkflowSuccessParameters") + public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, + Action action, int reqVersion) throws ValidationException, IOException { + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> customWorkflowSuccessParameters() + throws JsonParseException, JsonMappingException, IOException { + return Arrays.asList( + new Object[][] {{mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"} + + }); + } + + @Test + @Parameters(method = "aLaCarteParameters") + public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) + throws JsonParseException, IOException, ValidationException { + this.expected = expected; + this.sir = sir; + this.msoRequest = new MsoRequest(); + assertEquals(expected, msoRequest.getAlacarteFlag(sir)); + } + + @Parameters + private Collection<Object[]> aLaCarteParameters() throws IOException { + return Arrays.asList(new Object[][] { + {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class)}, + {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"), + ServiceInstancesRequest.class)}}); + } + + // Tests various scenarios ensuring that requests containing missing or invalid information will throw a + // ValidationException + @Test + @Parameters(method = "validationParameters") + public void validationFailureTest(String expectedException, ServiceInstancesRequest sir, + HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.expectedException = expectedException; + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + thrown.expect(ValidationException.class); + thrown.expectMessage(expectedException); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> validationParameters() throws IOException { + return Arrays.asList(new Object[][] { + // ValidationException for CloudConfiguration + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 4}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue( + inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid cloudConfiguration is specified", + mapper.readValue( + inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateAndCloudDelete, 7}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid lcpCloudRegionId is specified", + mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid lcpCloudRegionId is specified", + mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid tenantId is specified", + mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid tenantId is specified", + mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + // ValidationException for ModelInfo + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 4}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 6}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 6}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid model-info is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId format is specified", + mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 2}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 4}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 3}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 4}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, 4}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelType is specified", + mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 4}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 4}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + // ValidationException for Platform and LineOfBusiness + {"No valid lineOfBusinessName is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid platform is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 6}, + {"No valid platformName is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + // ValidationException for Project and OwningEntity + {"No valid owningEntity is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 6}, + {"No valid owningEntityId is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid projectName is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid owningEntity is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // ValidationException for RelatedInstances + {"No valid connectionPoint relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid connectionPoint relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid destination vnf relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceId format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceName format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceName in relatedInstance for pnf modelType is specified", + mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeRelationships, 6}, + {"No valid instanceName in relatedInstance for pnf modelType is specified", + mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 6}, + {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelInfo in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelName in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersion in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeRelationships, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 4}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid related service instance for vfModule request is specified", + mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related service instance for vnf request is specified", + mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related service instance for volumeGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related vnf instance for vfModule request is specified", + mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related vnf instance for volumeGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, 6}, + {"No valid source vnf relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid instanceName format is specified", + mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 2}, + {"No valid relatedInstanceList is specified", + mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid related service instance for instanceGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid modelVersionId in relatedInstance is specified", + mapper.readValue( + inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + // ValidationException for RequestInfo + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + // ValidationException for RequestParameters + {"No valid aLaCarte in requestParameters", + mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 4}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // ValidationException for SubscriberInfo + {"No valid globalSubscriberId is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriberInfo is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriptionServiceType is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriberInfo is specified", + mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // Validation for UserParams + {"No valid cloudConfiguration in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid cloudConfiguration in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams service modelInfo is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams vfModule resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid platform in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid platformName in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid productFamilyId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid vfModules in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModules.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams vfModules resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams vfModule resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // Validation for ConfigurationParameters + {"No valid configuration parameters is specified", + mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + // Validation for Add and Remove Members + {"No valid vnf relatedInstance is specified", + mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid source is specified", + mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid instanceId in relatedInstances is specified", + mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeMembers, 7}}); + } + + @Test + public void nullInstanceIdMapTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest = null; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(NullPointerException.class); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void serviceInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void vnfInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("vnfInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid vnfInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void vfModuleInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("vfModuleInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid vfModuleInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void volumeGroupInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("volumeGroupInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid volumeGroupInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void networkInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("networkInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid networkInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void configurationInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("configurationInstanceId", "test"); + this.action = Action.createInstance; + thrown.expect(ValidationException.class); + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expectMessage("No valid configurationInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void instanceGroupIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("instanceGroupInstanceId", "test"); + this.action = Action.createInstance; + thrown.expect(ValidationException.class); + this.reqVersion = 7; + this.version = "v" + reqVersion; + thrown.expectMessage("No valid instanceGroupInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void testVfModuleV4UsePreLoad() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json"); + this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.reqVersion = 4; + this.version = "v" + reqVersion; + this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); + this.msoRequest = new MsoRequest(); + msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, + false); + + this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json"); + this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); + msoRequest = new MsoRequest(); + msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, + false); + } + + @Test + public void buildServiceErrorResponseTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, + "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } - @Test - public void buildServiceErrorPolicyExceptionResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - - - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.PolicyException, "Mapping of request to JSON object failed. ", - ErrorNumbers.SVC_BAD_PARAMETER, null, version); + } + + @Test + public void buildServiceErrorPolicyExceptionResponseTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + + + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.PolicyException, + "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } + } @Test public void domToStrTest() throws Exception { @@ -531,17 +1040,18 @@ public class MsoRequestTest extends BaseTest { @Test public void buildSelfLinkUrlTest() throws Exception { - // v - version - String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; - String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1"; - this.msoRequest = new MsoRequest(); - Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId); - assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); - // V - Version - String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; - String expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId); - assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString()); - } -}
\ No newline at end of file + // v - version + String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; + String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; + String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1"; + this.msoRequest = new MsoRequest(); + Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId); + assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); + // V - Version + String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; + String expectedSelfLinkV = + "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; + Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId); + assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString()); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index e96558171d..321ea3ac7d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -31,7 +31,6 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -40,10 +39,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Ignore; import org.junit.Test; @@ -63,7 +60,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -73,8 +69,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class OrchestrationRequestsTest extends BaseTest { @Autowired private RequestsDbClient requestsDbClient; - - @Autowired + + @Autowired private OrchestrationRequests orchReq; private static final GetOrchestrationListResponse ORCHESTRATION_LIST = generateOrchestrationList(); @@ -113,13 +109,12 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); @@ -127,7 +122,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } - + @Test public void testGetOrchestrationRequestInstanceGroup() throws Exception { setupTestGetOrchestrationRequestInstanceGroup(); @@ -145,19 +140,18 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); } @Test public void testGetOrchestrationRequestRequestDetails() throws Exception { setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); - //Test request with modelInfo request body + // Test request with modelInfo request body GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest(); @@ -172,13 +166,12 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); @@ -188,12 +181,12 @@ public class OrchestrationRequestsTest extends BaseTest { @Test public void testGetOrchestrationRequestNoRequestID() { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json; charset=UTF-8"); - headers.set("Content-Type", "application/json; charset=UTF-8"); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json; charset=UTF-8"); + headers.set("Content-Type", "application/json; charset=UTF-8"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/")); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/")); ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationListResponse.class); @@ -206,10 +199,11 @@ public class OrchestrationRequestsTest extends BaseTest { List<String> values = new ArrayList<>(); values.add("EQUALS"); values.add("vfModule"); - + ObjectMapper mapper = new ObjectMapper(); - GetOrchestrationListResponse testResponse = mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"), - GetOrchestrationListResponse.class); + GetOrchestrationListResponse testResponse = + mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"), + GetOrchestrationListResponse.class); Map<String, List<String>> orchestrationMap = new HashMap<>(); orchestrationMap.put("modelType", values); @@ -219,18 +213,17 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule")); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule")); ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationListResponse.class); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("requestList.request.startTime").ignoring("requestList.request.finishTime") - .ignoring("requestList.request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("requestList.request.startTime") + .ignoring("requestList.request.finishTime").ignoring("requestList.request.requestStatus.timeStamp")); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals(requests.size(), response.getBody().getRequestList().size()); - + } @Test @@ -238,7 +231,8 @@ public class OrchestrationRequestsTest extends BaseTest { setupTestUnlockOrchestrationRequest("0017f68c-eb2d-45bb-b7c7-ec31b37dc349", "UNLOCKED"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -254,11 +248,12 @@ public class OrchestrationRequestsTest extends BaseTest { expectedRequestError = new RequestError(); se = new ServiceException(); se.setMessageId(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); - se.setText("Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked"); + se.setText( + "Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked"); expectedRequestError.setServiceException(se); - builder = UriComponentsBuilder.fromHttpUrl( - createURLWithPort("/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock")); + builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); actualRequestError = mapper.readValue(response.getBody(), RequestError.class); @@ -272,7 +267,8 @@ public class OrchestrationRequestsTest extends BaseTest { setupTestUnlockOrchestrationRequest_invalid_Json(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -306,7 +302,8 @@ public class OrchestrationRequestsTest extends BaseTest { throws JsonParseException, JsonMappingException, IOException, ValidationException { setupTestUnlockOrchestrationRequest_Valid_Status("5ffbabd6-b793-4377-a1ab-082670fbc7ac", "PENDING"); ObjectMapper mapper = new ObjectMapper(); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -318,14 +315,15 @@ public class OrchestrationRequestsTest extends BaseTest { // Test valid status request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); - builder = UriComponentsBuilder.fromHttpUrl( - createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); + builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - //Cannot assert anything further here, already have a wiremock in place which ensures that the post was properly called to update. + // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // properly called to update. } - @Ignore //What is this testing? + @Ignore // What is this testing? @Test public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception { InfraActiveRequests requests = new InfraActiveRequests(); @@ -346,8 +344,8 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -357,19 +355,20 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); } - @Ignore //What is this testing? + @Ignore // What is this testing? @Test public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException { InfraActiveRequests requests = new InfraActiveRequests(); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); + String requestJSON = new String( + Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); requests.setAction("create"); requests.setRequestBody(requestJSON); requests.setRequestId("requestId"); requests.setRequestScope("service"); requests.setRequestType("createInstance"); -// iar.save(requests); + // iar.save(requests); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -378,8 +377,8 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -388,96 +387,112 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); } + @Test - public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException{ - RequestProcessingData entry = new RequestProcessingData(); - RequestProcessingData secondEntry = new RequestProcessingData(); - List<HashMap<String, String>> expectedList = new ArrayList<>(); - HashMap<String, String> expectedMap = new HashMap<>(); - List<HashMap<String, String>> secondExpectedList = new ArrayList<>(); - HashMap<String, String> secondExpectedMap = new HashMap<>(); - List<RequestProcessingData> expectedDataList = new ArrayList<>(); - entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); - entry.setTag("pincFabricConfigRequest"); - expectedMap.put("requestAction", "assign"); - expectedMap.put("pincFabricId", "testId"); - expectedList.add(expectedMap); - entry.setDataPairs(expectedList); - secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715"); - secondEntry.setTag("pincFabricConfig"); - secondExpectedMap.put("requestAction", "unassign"); - secondExpectedList.add(secondExpectedMap); - secondEntry.setDataPairs(secondExpectedList); - expectedDataList.add(entry); - expectedDataList.add(secondEntry); - - List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>(); - List<RequestProcessingData> actualProcessingData = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - processingData = mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"), - new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>(){}); + public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { + RequestProcessingData entry = new RequestProcessingData(); + RequestProcessingData secondEntry = new RequestProcessingData(); + List<HashMap<String, String>> expectedList = new ArrayList<>(); + HashMap<String, String> expectedMap = new HashMap<>(); + List<HashMap<String, String>> secondExpectedList = new ArrayList<>(); + HashMap<String, String> secondExpectedMap = new HashMap<>(); + List<RequestProcessingData> expectedDataList = new ArrayList<>(); + entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); + entry.setTag("pincFabricConfigRequest"); + expectedMap.put("requestAction", "assign"); + expectedMap.put("pincFabricId", "testId"); + expectedList.add(expectedMap); + entry.setDataPairs(expectedList); + secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715"); + secondEntry.setTag("pincFabricConfig"); + secondExpectedMap.put("requestAction", "unassign"); + secondExpectedList.add(secondExpectedMap); + secondEntry.setDataPairs(secondExpectedList); + expectedDataList.add(entry); + expectedDataList.add(secondEntry); + + List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>(); + List<RequestProcessingData> actualProcessingData = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + processingData = + mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"), + new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>() {}); actualProcessingData = orchReq.mapRequestProcessingData(processingData); - assertThat(actualProcessingData,sameBeanAs(expectedDataList)); + assertThat(actualProcessingData, sameBeanAs(expectedDataList)); } - public void setupTestGetOrchestrationRequest() throws Exception{ - //For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) - .withStatus(HttpStatus.SC_OK))); + public void setupTestGetOrchestrationRequest() throws Exception { + // For testGetOrchestrationRequest + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) + .withStatus(HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) + .withStatus(HttpStatus.SC_OK))); } - public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception{ - //For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) - .withStatus(HttpStatus.SC_OK))); + + public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception { + // For testGetOrchestrationRequest + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths.get( + "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) + .withStatus(HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) + .withStatus(HttpStatus.SC_OK))); } - private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception{ - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json")))) + private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json")))) .withStatus(HttpStatus.SC_OK))); } private void setupTestUnlockOrchestrationRequest(String requestId, String status) { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, requestId, status)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK))); } private void setupTestUnlockOrchestrationRequest_invalid_Json() { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); } private void setupTestUnlockOrchestrationRequest_Valid_Status(String requestID, String status) { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, requestID, status)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestID))) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, requestID, status)).withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(infraActivePost, requestID)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(infraActivePost, requestID)).withStatus(HttpStatus.SC_OK))); } - private void setupTestGetOrchestrationRequestFilter() throws Exception{ - //for testGetOrchestrationRequestFilter(); - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/")).withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json")))) - .withStatus(HttpStatus.SC_OK))); + private void setupTestGetOrchestrationRequestFilter() throws Exception { + // for testGetOrchestrationRequestFilter(); + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/")) + .withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json")))) + .withStatus(HttpStatus.SC_OK))); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java index a5f9514be2..dc0cd473c2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java @@ -32,20 +32,16 @@ import static org.junit.Assert.assertTrue; 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.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; - import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Before; - import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; @@ -65,7 +61,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -73,92 +68,91 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class RequestHandlerUtilsTest extends BaseTest{ +public class RequestHandlerUtilsTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); - private final ObjectMapper mapper = new ObjectMapper(); - private ObjectMapper errorMapper = new ObjectMapper(); - @Autowired private RequestHandlerUtils requestHandlerUtils; - @Value("${wiremock.server.port}") - private String wiremockPort; - + @Value("${wiremock.server.port}") + private String wiremockPort; + 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); + @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 = 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{ + 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))); } - - 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); - } + + 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); + 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()); + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); } @Test - public void test_mapJSONtoMSOStyle() throws IOException{ + public void test_mapJSONtoMSOStyle() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); + String testRequest = inputStream("/ServiceInstanceDefault.json"); String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, null, false, null); ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class); ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796",modelInfo.getModelCustomizationUuid()); - assertEquals("modelInstanceName",modelInfo.getModelInstanceName()); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965",modelInfo.getModelInvariantUuid()); - assertEquals("10",modelInfo.getModelUuid()); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796", modelInfo.getModelCustomizationUuid()); + assertEquals("modelInstanceName", modelInfo.getModelInstanceName()); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965", modelInfo.getModelInvariantUuid()); + assertEquals("10", modelInfo.getModelUuid()); } - - + + @Test - public void test_mapJSONtoMSOStyleUsePreload() throws IOException{ + public void test_mapJSONtoMSOStyleUsePreload() throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); + String testRequest = inputStream("/ServiceInstanceDefault.json"); ServiceInstancesRequest sir = new ServiceInstancesRequest(); RequestDetails rd = new RequestDetails(); RequestParameters rp = new RequestParameters(); @@ -168,163 +162,178 @@ public class RequestHandlerUtilsTest extends BaseTest{ String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, sir, false, null); ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class); assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload()); - } - + } + @Test - public void setServiceTypeTestALaCarte() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = true; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setSource("VID"); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceTypeALaCarte"); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + public void setServiceTypeTestALaCarte() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = true; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceTypeALaCarte"); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceTypeALaCarte"); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceTypeALaCarte"); } + @Test - public void setServiceTypeTest() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + public void setServiceTypeTest() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); } + @Test - public void setServiceTypeTestDefault() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + public void setServiceTypeTestDefault() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_NOT_FOUND))); - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); } + @Test - public void setServiceTypeTestNetwork() throws JsonProcessingException{ - String requestScope = ModelType.network.toString(); - Boolean aLaCarteFlag = null; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelName("networkModelName"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - - String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "networkModelName"); + public void setServiceTypeTestNetwork() throws JsonProcessingException { + String requestScope = ModelType.network.toString(); + Boolean aLaCarteFlag = null; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelName("networkModelName"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "networkModelName"); } + @Test - public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException{ - String requestScope = "instanceGroup"; - ServiceInstancesRequest sir = mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); - assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException { + String requestScope = "instanceGroup"; + ServiceInstancesRequest sir = + mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); + assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); } + @Test - public void setServiceInstanceIdTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + public void setServiceInstanceIdTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); } + @Test - public void setServiceInstanceIdReturnNullTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + public void setServiceInstanceIdReturnNullTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); } + @Test - public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException{ - wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); - assertTrue(inProgress); + public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertTrue(inProgress); } + @Test - public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException{ - wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); + public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); } + @Test - public void camundaHistoryCheckNotInProgressTest()throws ContactCamundaException, RequestDbFailureException{ - wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponseCompleted.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); + public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponseCompleted.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); } + @Test - public void setCamundaHeadersTest()throws ContactCamundaException, RequestDbFailureException{ - String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password - String key = "07a7159d3bf51a0e53be7a8f89699be7"; - HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); - List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); - String expectedAcceptedType = "application/json"; - assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); - String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); - String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; - assertEquals(expectedBasicAuth, basicAuth); - } - + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + assertEquals(expectedBasicAuth, basicAuth); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java index 33d9d413d6..328414930e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra; import java.util.List; - import org.junit.Before; import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.filters.FilterEnum; import com.openpojo.reflection.impl.PojoClassFactory; @@ -34,17 +32,19 @@ import com.openpojo.validation.rule.impl.*; import com.openpojo.validation.test.impl.*; -public class ServiceInstanceBeansTest extends BaseTest{ - List<PojoClass> pojoClasses; - @Before - public void setup() { - pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum()); - } - @Test - public void validateGettersAndSetters() { - Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) - .with(new SetterTester(), new GetterTester()).build(); - validator.validate(pojoClasses); - } +public class ServiceInstanceBeansTest extends BaseTest { + List<PojoClass> pojoClasses; + + @Before + public void setup() { + pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum()); + } + + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate(pojoClasses); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index d3899fd318..1bb3932cff 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -42,8 +42,6 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; - - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -52,10 +50,8 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; - 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; @@ -78,7 +74,6 @@ 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.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -86,20 +81,19 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class ServiceInstancesTest extends BaseTest{ +public class ServiceInstancesTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); - private final ObjectMapper mapper = new ObjectMapper(); - private ObjectMapper errorMapper = new ObjectMapper(); - @Autowired private ServiceInstances servInstances; - - @Value("${wiremock.server.port}") - private String wiremockPort; + + @Value("${wiremock.server.port}") + private String wiremockPort; private final String servInstanceuri = "/onap/so/infra/serviceInstantiation/"; private final String servInstanceUriPrev7 = "/onap/so/infra/serviceInstances/"; @@ -109,79 +103,79 @@ public class ServiceInstancesTest extends BaseTest{ 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); + @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 = 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{ + 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); - } + 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); + 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()); + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); } - + @Test - public void createServiceInstanceVIDDefault() throws IOException{ + public void createServiceInstanceVIDDefault() throws IOException { TestAppender.events.clear(); ServiceRecipe serviceRecipe = new ServiceRecipe(); @@ -192,68 +186,67 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); - - - - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + + + + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS",mdc.get(STATUSCODE)); - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME)); + assertEquals("INPROGRESS", mdc.get(STATUSCODE)); + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ENDTIME)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202",mdc.get(RESPONSECODE)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE",mdc.get(STATUSCODE)); + assertEquals("202", mdc.get(RESPONSECODE)); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME)); + assertEquals("COMPLETE", mdc.get(STATUSCODE)); assertNotNull(mdc.get(RESPONSEDESC)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); } } + @Test - public void createServiceInstanceServiceInstancesUri() throws IOException{ + public void createServiceInstanceServiceInstancesUri() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/CreateGenericALaCarteServiceInstance"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -262,37 +255,37 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateGenericALaCarteServiceInstance")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expect + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceUriPrev7 + "v5"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void createServiceInstanceBpelStatusError() throws IOException{ + public void createServiceInstanceBpelStatusError() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -303,486 +296,505 @@ public class ServiceInstancesTest extends BaseTest{ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createServiceInstanceBadGateway() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - + public void createServiceInstanceBadGateway() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY).withBody("{}"))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createServiceInstanceEmptyResponse() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - + public void createServiceInstanceEmptyResponse() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEmpty.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstanceNoRecipeALaCarte() throws IOException{ - TestAppender.events.clear(); + public void activateServiceInstanceNoRecipeALaCarte() throws IOException { + TestAppender.events.clear(); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; - HttpHeaders requestIDheaders = new HttpHeaders(); - requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri, HttpMethod.POST, requestIDheaders); + HttpHeaders requestIDheaders = new HttpHeaders(); + requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri, + HttpMethod.POST, requestIDheaders); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + + wireMockServer.stubFor(get(urlMatching( + ".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstanceNoRecipe() throws IOException{ + public void activateServiceInstanceNoRecipe() throws IOException { uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/.*")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstance() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void activateServiceInstance() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceActivate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deactivateServiceInstance() throws IOException{ + public void deactivateServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/deactivate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDeactivate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a8868/"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void assignServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/assign"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceAssign.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceAssign.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void unassignServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/unassign"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceUnassign.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceUnassign.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createPortConfiguration() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePortConfiguration.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createPortConfigurationEmptyProductFamilyId() throws IOException { uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void deletePortConfiguration() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void enablePort() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEnablePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceEnablePort.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")); } + @Test public void disablePort() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDisablePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDisablePort.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")); } + @Test public void activatePort() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivatePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceActivatePort.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")); } + @Test public void deactivatePort() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivatePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDeactivatePort.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")); } + @Test public void addRelationships() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/addRelationships"; - ResponseEntity<String> response = sendRequest(inputStream("/AddRelationships.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/AddRelationships.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void removeRelationships() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/removeRelationships"; - ResponseEntity<String> response = sendRequest(inputStream("/RemoveRelationships.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/RemoveRelationships.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVnfInstanceNoALaCarte() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -790,34 +802,39 @@ public class ServiceInstancesTest extends BaseTest{ .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomization_ReplaceVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/49585b36-2b5a-443a-8b10-c75d34bb5e46/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfCreateDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfCreateDefault.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVnfInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -832,281 +849,317 @@ public class ServiceInstancesTest extends BaseTest{ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationsList_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstance.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfWithServiceRelatedInstance.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createVnfWithServiceRelatedInstanceFail() throws IOException { uri = servInstanceUriPrev7 + "v6" + "/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createVnfInstanceInvalidVnfResource() throws IOException { + public void createVnfInstanceInvalidVnfResource() throws IOException { uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs"; ResponseEntity<String> response = sendRequest(inputStream("/NoVnfResource.json"), uri, HttpMethod.POST); - + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vnfResource is specified", realResponse.getServiceException().getText()); } + @Test public void replaceVnfInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomization_ReplaceVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnf.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void replaceVnfRecreateInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/RecreateInfraVce")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; - ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + ResponseEntity<String> response = + sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void recreateVnfInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate"; ResponseEntity<String> response = sendRequest(inputStream("/VnfRecreate.json"), uri, HttpMethod.POST, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void updateVnfInstance() throws IOException { + public void updateVnfInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateVnf.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void applyUpdatedConfig() throws IOException { + public void applyUpdatedConfig() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfConfigUpdate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig"; - ResponseEntity<String> response = sendRequest(inputStream("/ApplyUpdatedConfig.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig"; + ResponseEntity<String> response = + sendRequest(inputStream("/ApplyUpdatedConfig.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVnfInstanceV5() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_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("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v5" + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v5" + + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVfModuleInstance() throws IOException { - wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching("/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching( + "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=20c4431c-246d-11e7-93ae-92361f002671")) + wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) + + wireMockServer.stubFor(get(urlMatching( + "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=20c4431c-246d-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching("/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + "/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleWithRelatedInstances.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleWithRelatedInstances.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createVfModuleInstanceNoModelCustomization() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) @@ -1118,24 +1171,28 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + - "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc[?]" + - "MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672&MODEL_UUID=066de97e-253e-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc[?]" + + "MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672&MODEL_UUID=066de97e-253e-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -1146,25 +1203,30 @@ public class ServiceInstancesTest extends BaseTest{ .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction" + - "[?]vnfComponentType=vfModule&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVNF_API_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction" + + "[?]vnfComponentType=vfModule&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVNF_API_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("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ObjectMapper mapper = new ObjectMapper(); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVfModuleInstanceNoMatchingModelUUD() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -1176,22 +1238,25 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -1201,27 +1266,32 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_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("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ObjectMapper mapper = new ObjectMapper(); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVfModuleInstanceNoRecipe() throws IOException { @@ -1230,72 +1300,86 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + - "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" + - "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers); - + wireMockServer.stubFor( + get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" + + "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vfModuleCustomization is specified", realResponse.getServiceException().getText()); } + @Test public void replaceVfModuleInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; - ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVfModule.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + ResponseEntity<String> response = + sendRequest(inputStream("/ReplaceVfModule.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateVfModuleInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -1305,28 +1389,33 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipe_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void createVfModuleNoModelType() throws IOException{ + public void createVfModuleNoModelType() throws IOException { InfraActiveRequests expectedRecord = new InfraActiveRequests(); expectedRecord.setRequestStatus("FAILED"); expectedRecord.setAction("createInstance"); @@ -1341,198 +1430,231 @@ public class ServiceInstancesTest extends BaseTest{ expectedRecord.setRequestAction("createInstance"); expectedRecord.setRequestorId("zz9999"); expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d"); - //VnfType is not sent in this request, should be blank in db + // VnfType is not sent in this request, should be blank in db expectedRecord.setVnfType(""); - uri = servInstanceuri + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules"; + uri = servInstanceuri + + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers); - //ActualRecord + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers); + // ActualRecord assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void inPlaceSoftwareUpdate() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" + - "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" + + "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate"; - ResponseEntity<String> response = sendRequest(inputStream("/InPlaceSoftwareUpdate.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate"; + ResponseEntity<String> response = + sendRequest(inputStream("/InPlaceSoftwareUpdate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } - + @Test public void deleteVfModuleInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVfModuleNoModelInvariantId() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deactivateAndCloudDeleteVfModuleInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeactivate_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeactivate_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete"; - ResponseEntity<String> response = sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.json"), uri, HttpMethod.POST, headers); - + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVolumeGroupInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups"; ResponseEntity<String> response = sendRequest(inputStream("/VolumeGroup.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void updateVolumeGroupInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVolumeGroupInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -1543,35 +1665,41 @@ public class ServiceInstancesTest extends BaseTest{ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createNetworkInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -1583,30 +1711,33 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateNetworkInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -1618,30 +1749,33 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void deleteNetworkInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -1653,59 +1787,66 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteNetworkInstanceNoReqParams() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void convertJsonToServiceInstanceRequestFail() throws IOException { - //ExpectedRecord + // ExpectedRecord InfraActiveRequests expectedRecord = new InfraActiveRequests(); expectedRecord.setRequestStatus("FAILED"); expectedRecord.setStatusMessage("Error mapping request: "); @@ -1716,16 +1857,20 @@ public class ServiceInstancesTest extends BaseTest{ expectedRecord.setRequestAction("deleteInstance"); expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d"); - uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers); - //ActualRecord + // ActualRecord assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void convertJsonToServiceInstanceRequestConfigurationFail() throws IOException { - uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort"; + uri = servInstanceuri + "v5" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort"; ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); @@ -1745,30 +1890,29 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -1782,30 +1926,32 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -1815,9 +1961,10 @@ public class ServiceInstancesTest extends BaseTest{ .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); @@ -1837,30 +1984,32 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -1874,34 +2023,36 @@ public class ServiceInstancesTest extends BaseTest{ .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test - public void activateServiceInstanceRequestStatus() throws IOException{ + public void activateServiceInstanceRequestStatus() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -1910,33 +2061,32 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - //expect + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7999/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev8.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePrev8.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -1945,13 +2095,15 @@ public class ServiceInstancesTest extends BaseTest{ HttpHeaders ivalidRequestIdHeaders = new HttpHeaders(); ivalidRequestIdHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, illegalRequestId); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); assertTrue(response.getBody().contains("Request Id " + illegalRequestId + " is not a valid UUID")); } + @Test - public void invalidBPELResponse() throws IOException{ + public void invalidBPELResponse() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -1961,30 +2113,31 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", realResponse.getServiceException().getText()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", + realResponse.getServiceException().getText()); } + @Test - public void unauthorizedBPELResponse() throws IOException{ + public void unauthorizedBPELResponse() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -1994,31 +2147,32 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/UnauthorizedResponse.json").withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED))); + .withBodyFile("Camunda/UnauthorizedResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); + assertEquals("Exception caught mapping Camunda JSON response to object", + realResponse.getServiceException().getText()); } @Test - public void invalidBPELResponse2() throws IOException{ + public void invalidBPELResponse2() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -2028,30 +2182,30 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("<aetgt:ErrorMessage>Exception in create execution list 500")); + assertTrue(realResponse.getServiceException().getText() + .contains("<aetgt:ErrorMessage>Exception in create execution list 500")); } @Test - public void createMacroServiceInstance() throws IOException{ + public void createMacroServiceInstance() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/CreateMacroServiceNetworkVnf"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -2060,44 +2214,44 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceUriPrev7 + "v5"; - ResponseEntity<String> response = sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void testUserParams() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); RequestParameters requestParameters = request.getRequestDetails().getRequestParameters(); String userParamsTxt = inputStream("/userParams.txt"); @@ -2112,8 +2266,10 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void testConfigureCloudConfig() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); - CloudConfiguration cloudConfig = servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters()); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + CloudConfiguration cloudConfig = + servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters()); assertEquals("mdt25b", cloudConfig.getLcpCloudRegionId()); assertEquals("aefb697db6524ddebfe4915591b0a347", cloudConfig.getTenantId()); @@ -2122,24 +2278,28 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void testMapToLegacyRequest() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); - ServiceInstancesRequest expected = mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest expected = + mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class); servInstances.mapToLegacyRequest(request.getRequestDetails()); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request)); assertThat(request, sameBeanAs(expected)); } + @Test public void scaleOutVfModule() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -2150,125 +2310,152 @@ public class ServiceInstancesTest extends BaseTest{ .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVfModuleScaleOut_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVfModuleScaleOut_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut"; - ResponseEntity<String> response = sendRequest(inputStream("/ScaleOutRequest.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut"; + ResponseEntity<String> response = + sendRequest(inputStream("/ScaleOutRequest.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test - public void createServiceInstanceBadResponse() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); - } - @Test - public void createServiceInstanceDuplicateError() throws IOException{ - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + public void createServiceInstanceBadResponse() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + assertEquals("Exception caught mapping Camunda JSON response to object", + realResponse.getServiceException().getText()); + } + + @Test + public void createServiceInstanceDuplicateError() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + + uri = servInstanceuri + "v5/serviceInstances"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicateHistoryCheck() throws IOException{ - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") - .withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + public void createServiceInstanceDuplicateHistoryCheck() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - + .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.", realResponse.getServiceException().getText()); + assertEquals( + "Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicateHistoryCheckException() throws IOException{ - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") - .withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + public void createServiceInstanceDuplicateHistoryCheckException() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicate() throws IOException{ - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + public void createServiceInstanceDuplicate() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } - + @Test - public void createServiceInstanceSaveError() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); + public void createServiceInstanceSaveError() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); serviceRecipe.setAction(Action.createInstance.toString()); @@ -2276,218 +2463,241 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test public void createPortConfigurationSaveError() throws IOException { - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - + uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test public void createPortConfigDbUpdateError() throws IOException { - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void vnfUpdateWithNetworkInstanceGroup() throws IOException{ - TestAppender.events.clear(); - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void vnfUpdateWithNetworkInstanceGroup() throws IOException { + TestAppender.events.clear(); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=2ccae1b4-7d9e-46fa-a452-9180ce008d17")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=2ccae1b4-7d9e-46fa-a452-9180ce008d17")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "VID"); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers); - //then + uri = servInstanceuri + + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca"; + ResponseEntity<String> response = + sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers); + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertEquals(response.getHeaders().get(TRANSACTION_ID).get(0), "32807a28-1a14-4b88-b7b3-2950918aa76d"); - - for(ILoggingEvent logEvent : TestAppender.events){ - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertEquals("VID",mdc.get(PARTNERNAME)); + + for (ILoggingEvent logEvent : TestAppender.events) { + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("VID", mdc.get(PARTNERNAME)); } } } + @Test - public void createInstanceGroup() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void createInstanceGroup() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expect + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups"; - ResponseEntity<String> response = sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deleteInstanceGroup() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void deleteInstanceGroup() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expect + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deleteInstanceGroupNoRequestIdHeader() throws IOException{ + public void deleteInstanceGroupNoRequestIdHeader() throws IOException { uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE); - //then + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified"); } + @Test - public void deleteInstanceGroupNoPartnerNameHeader() throws IOException{ - HttpHeaders noPartnerHeaders = new HttpHeaders(); - noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx"); + public void deleteInstanceGroupNoPartnerNameHeader() throws IOException { + HttpHeaders noPartnerHeaders = new HttpHeaders(); + noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); + noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx"); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noPartnerHeaders); - //then + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified"); } + @Test - public void deleteInstanceGroupNoRquestorIdHeader() throws IOException{ + public void deleteInstanceGroupNoRquestorIdHeader() throws IOException { HttpHeaders noRequestorIdHheaders = new HttpHeaders(); noRequestorIdHheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - //expect + noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noRequestorIdHheaders); - - //then + + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified"); } + @Test - public void addMembers() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void addMembers() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/addMembers"; ResponseEntity<String> response = sendRequest(inputStream("/AddMembers.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void removeMembers() throws IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void removeMembers() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/removeMembers"; - ResponseEntity<String> response = sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteNetworkInstanceNoCustomizationEntry() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -2498,38 +2708,43 @@ public class ServiceInstancesTest extends BaseTest{ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_NOT_FOUND))); - wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_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("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateNetworkInstanceNoCustomizationEntry() throws IOException { - wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_NOT_FOUND))); - - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers); - + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); + assertEquals(realResponse.getServiceException().getText(), + "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); } - - + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java index 327141e0f2..77d6f68de9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java @@ -27,15 +27,12 @@ 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 java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.json.JSONException; import org.junit.Test; @@ -47,78 +44,80 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class TasksHandlerTest extends BaseTest{ - - private final String basePath = "onap/so/infra/tasks/v1"; - - @Test - public void getTasksTestByOriginalRequestId() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException{ - wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK))); - - String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a"; - - //expected response - TasksGetResponse expectedResponse = new TasksGetResponse(); - - List<TaskList> taskList = new ArrayList<TaskList>(); - TaskList taskList1 = new TaskList(); - List<String> validEntries = new ArrayList<String>(); - validEntries.add(ValidResponses.rollback.toString()); - validEntries.add(ValidResponses.skip.toString()); - validEntries.add(ValidResponses.manual.toString()); - validEntries.add(ValidResponses.abort.toString()); - taskList1.setBuildingBlockName("UpdateConfigurationState"); - taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check"); - taskList1.setErrorCode("1002"); - taskList1.setErrorSource("SDNO"); - taskList1.setErrorMessage("SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found"); - taskList1.setNfRole("VPROBE"); - taskList1.setType("fallout"); - taskList1.setOriginalRequestId(requestId); - taskList1.setOriginalRequestorId("VID"); - taskList1.setSubscriptionServiceType("PORT-MIRROR"); - taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52"); - taskList1.setDescription("test task"); - taskList1.setTimeout("PT3000S"); - taskList1.setValidResponses(validEntries); - taskList.add(taskList1); - - expectedResponse.setTaskList(taskList); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) - .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - ObjectMapper mapper = new ObjectMapper(); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - - //then - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); +public class TasksHandlerTest extends BaseTest { + + private final String basePath = "onap/so/infra/tasks/v1"; + + @Test + public void getTasksTestByOriginalRequestId() + throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK))); + + String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a"; + + // expected response + TasksGetResponse expectedResponse = new TasksGetResponse(); + + List<TaskList> taskList = new ArrayList<TaskList>(); + TaskList taskList1 = new TaskList(); + List<String> validEntries = new ArrayList<String>(); + validEntries.add(ValidResponses.rollback.toString()); + validEntries.add(ValidResponses.skip.toString()); + validEntries.add(ValidResponses.manual.toString()); + validEntries.add(ValidResponses.abort.toString()); + taskList1.setBuildingBlockName("UpdateConfigurationState"); + taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check"); + taskList1.setErrorCode("1002"); + taskList1.setErrorSource("SDNO"); + taskList1.setErrorMessage( + "SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found"); + taskList1.setNfRole("VPROBE"); + taskList1.setType("fallout"); + taskList1.setOriginalRequestId(requestId); + taskList1.setOriginalRequestorId("VID"); + taskList1.setSubscriptionServiceType("PORT-MIRROR"); + taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52"); + taskList1.setDescription("test task"); + taskList1.setTimeout("PT3000S"); + taskList1.setValidResponses(validEntries); + taskList.add(taskList1); + + expectedResponse.setTaskList(taskList); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + ObjectMapper mapper = new ObjectMapper(); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + + // then + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } + } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java index 48711a2595..1beb3b37a7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java @@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase; -public class TestAppender extends AppenderBase<ILoggingEvent> { +public class TestAppender extends AppenderBase<ILoggingEvent> { public static List<ILoggingEvent> events = new ArrayList<>(); - - @Override - protected void append(ILoggingEvent loggingEvent) { - events.add(loggingEvent); - } + + @Override + protected void append(ILoggingEvent loggingEvent) { + events.add(loggingEvent); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java index 760532e6fe..7678de1a19 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -23,15 +23,12 @@ package org.onap.so.apihandlerinfra; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.ParseException; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.json.JSONException; import org.junit.Test; import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications; @@ -40,43 +37,44 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class WorkflowSpecificationsHandlerTest extends BaseTest{ - - private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows"; - - @Test - public void getTasksTestByOriginalRequestId() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException{ - - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) - .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - ObjectMapper mapper = new ObjectMapper(); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - WorkflowSpecifications expectedResponse = mapper.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))), WorkflowSpecifications.class); +public class WorkflowSpecificationsHandlerTest extends BaseTest { + + private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows"; + + @Test + public void getTasksTestByOriginalRequestId() + throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + ObjectMapper mapper = new ObjectMapper(); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + WorkflowSpecifications expectedResponse = mapper.readValue( + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/WorkflowSpecifications.json"))), + WorkflowSpecifications.class); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java index 96ac02ae75..bc5869e416 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class DelE2ESvcRespTest { @@ -31,7 +30,7 @@ public class DelE2ESvcRespTest { @Test public void verifyDelE2ESvcResp() throws Exception { test.setOperationId("operationId"); - assertEquals(test.getOperationId(),"operationId"); + assertEquals(test.getOperationId(), "operationId"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java index 7cfee66d48..cbc835dfbb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class E2ERequestTest { @@ -32,23 +31,23 @@ public class E2ERequestTest { public void verifyE2ERequest() throws Exception { test.setOperationId("operationId"); - assertEquals(test.getOperationId(),"operationId"); + assertEquals(test.getOperationId(), "operationId"); test.setOperation("operation"); - assertEquals(test.getOperation(),"operation"); + assertEquals(test.getOperation(), "operation"); test.setResult("result"); - assertEquals(test.getResult(),"result"); + assertEquals(test.getResult(), "result"); test.setReason("test"); - assertEquals(test.getReason(),"test"); + assertEquals(test.getReason(), "test"); test.setUserId("userId"); - assertEquals(test.getUserId(),"userId"); + assertEquals(test.getUserId(), "userId"); test.setOperationContent("operation"); - assertEquals(test.getOperationContent(),"operation"); + assertEquals(test.getOperationContent(), "operation"); test.setProgress(123); - assertEquals(test.getProgress(),123); + assertEquals(test.getProgress(), 123); test.setOperateAt("operate"); - assertEquals(test.getOperateAt(),"operate"); + assertEquals(test.getOperateAt(), "operate"); test.setFinishedAt("finished"); - assertEquals(test.getFinishedAt(),"finished"); + assertEquals(test.getFinishedAt(), "finished"); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java index a3bab01dfd..8dfe6dc006 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class E2EServiceInstanceDeleteRequestTest { @@ -33,9 +32,9 @@ public class E2EServiceInstanceDeleteRequestTest { public void verifyE2ESerInstanceDelReq() throws Exception { test.setGlobalSubscriberId("id"); - assertEquals(test.getGlobalSubscriberId(),"id"); + assertEquals(test.getGlobalSubscriberId(), "id"); test.setServiceType("type"); - assertEquals(test.getServiceType(),"type"); + assertEquals(test.getServiceType(), "type"); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java index 59bfa2a1d2..bb331904ca 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import java.util.HashMap; import java.util.Map; - import static org.junit.Assert.assertEquals; public class E2EUserParamTest { @@ -35,13 +33,13 @@ public class E2EUserParamTest { public void verifyE2EParam() throws Exception { test.setName("name"); - assertEquals(test.getName(),"name"); + assertEquals(test.getName(), "name"); test.setValue("value"); - assertEquals(test.getValue(),"value"); + assertEquals(test.getValue(), "value"); Map<String, Object> additionalProperties = new HashMap<>(); additionalProperties.put("name", test); - test.setAdditionalProperty("name",test); - assertEquals(test.getAdditionalProperties(),additionalProperties); + test.setAdditionalProperty("name", test); + assertEquals(test.getAdditionalProperties(), additionalProperties); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java index 59e10b3938..5b09cefc85 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java @@ -21,12 +21,10 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import static org.junit.Assert.assertEquals; public class NsParametersTest { @@ -37,15 +35,15 @@ public class NsParametersTest { @Test public void verifyNsParameters() throws Exception { - LocationConstraint obj =new LocationConstraint(); + LocationConstraint obj = new LocationConstraint(); List<LocationConstraint> locationConstraints = new ArrayList<LocationConstraint>(); locationConstraints.add(obj); test.setLocationConstraints(locationConstraints); - assertEquals(test.getLocationConstraints(),locationConstraints); - Map<String, Object> additionalParamForNs = new HashMap<String,Object>(); - additionalParamForNs.put("1",test); + assertEquals(test.getLocationConstraints(), locationConstraints); + Map<String, Object> additionalParamForNs = new HashMap<String, Object>(); + additionalParamForNs.put("1", test); test.setAdditionalParamForNs(additionalParamForNs); - assertEquals(test.getAdditionalParamForNs(),additionalParamForNs); + assertEquals(test.getAdditionalParamForNs(), additionalParamForNs); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java index cbdfe6b831..9c7fd37d28 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tasksbeans; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; - import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; @@ -31,11 +30,11 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; -public class TasksBeansTest extends BaseTest{ - @Test - public void validateGettersAndSetters() { - Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) - .with(new SetterTester(), new GetterTester()).build(); - validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); - } +public class TasksBeansTest extends BaseTest { + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java index 5c5a9e92b3..9ae1e5b232 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java @@ -27,12 +27,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - import java.io.File; import java.io.IOException; - import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Ignore; @@ -47,207 +44,242 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.databind.ObjectMapper; public class CloudOrchestrationTest extends BaseTest { - - private static final String path = "/onap/so/infra/cloudResources/v1"; - - private HttpHeaders headers = new HttpHeaders(); - - @Before - public void setupTestClass() throws Exception{ - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED))); - } - - @Test - public void testCreateOpEnvObjectMapperError() throws IOException { - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody().toString(); - assertTrue(body.contains("Mapping of request to JSON object failed.")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testCreateOpEnvError() throws IOException { - - String request = "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"}," - + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody().toString(); - assertTrue(body.contains("Mapping of request to JSON object failed")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException { - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "123", "PENDING")) - .withStatus(HttpStatus.SC_OK))); - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(409, response.getStatusCodeValue()); - } - - @Test - public void testCreateOperationalEnvironment() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - headers.set("X-TransactionID", "987654321"); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testCreateVNFDuplicateCheck() throws IOException { - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString())) - .withStatus(HttpStatus.SC_OK))); - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(409, response.getStatusCodeValue()); - } - - @Test - public void testCreateVNF() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testActivate() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate"); - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testDeactivate() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), TenantIsolationRequest.class); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - -// wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) -// .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa", Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); - } - - - @Test - @Ignore - public void testDeactivateDupCheck() throws IOException { - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestId"); - iar.setOperationalEnvName("myVnfOpEnv"); - iar.setRequestStatus(Status.IN_PROGRESS.toString()); - iar.setAction(Action.create.toString()); - iar.setRequestAction(Action.create.toString()); - iar.setRequestScope("UNKNOWN"); - //iarRepo.saveAndFlush(iar); - ObjectMapper mapper = new ObjectMapper(); - String request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(409, response.getStatusCodeValue()); - } - -}
\ No newline at end of file + + private static final String path = "/onap/so/infra/cloudResources/v1"; + + private HttpHeaders headers = new HttpHeaders(); + + @Before + public void setupTestClass() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_CREATED))); + } + + @Test + public void testCreateOpEnvObjectMapperError() throws IOException { + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody().toString(); + assertTrue(body.contains("Mapping of request to JSON object failed.")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testCreateOpEnvError() throws IOException { + + String request = + "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"}," + + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody().toString(); + assertTrue(body.contains("Mapping of request to JSON object failed")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "123", "PENDING")).withStatus(HttpStatus.SC_OK))); + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(409, response.getStatusCodeValue()); + } + + @Test + public void testCreateOperationalEnvironment() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set("X-TransactionID", "987654321"); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testCreateVNFDuplicateCheck() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString())) + .withStatus(HttpStatus.SC_OK))); + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(409, response.getStatusCodeValue()); + } + + @Test + public void testCreateVNF() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testActivate() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + + wireMockServer.stubFor( + get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testDeactivate() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), + TenantIsolationRequest.class); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + + // wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, + // MediaType.APPLICATION_JSON) + // .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa", + // Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); + } + + + @Test + @Ignore + public void testDeactivateDupCheck() throws IOException { + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestId"); + iar.setOperationalEnvName("myVnfOpEnv"); + iar.setRequestStatus(Status.IN_PROGRESS.toString()); + iar.setAction(Action.create.toString()); + iar.setRequestAction(Action.create.toString()); + iar.setRequestScope("UNKNOWN"); + // iarRepo.saveAndFlush(iar); + ObjectMapper mapper = new ObjectMapper(); + String request = mapper.readValue( + new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(request, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(409, response.getStatusCodeValue()); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java index c119653ae3..5f12060059 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java @@ -26,11 +26,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - import java.text.ParseException; - import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -43,272 +40,283 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; -public class CloudResourcesOrchestrationTest extends BaseTest{ - - private String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }"; - private static final String path = "/onap/so/infra/cloudResourcesRequests"; - - HttpHeaders headers = new HttpHeaders(); - @Before - public void setupTestClass() throws Exception{ - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED))); - } - @Test - public void testUnlockFailObjectMapping() { - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody(); - assertTrue(body.contains("Mapping of request to JSON object failed.")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError1() { - String requestJSON = "{\"requestDetails\": null }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid requestDetails is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError2() { - String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid source is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError3() { - String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid requestorId is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testGetInfraActiveRequestNull() { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB")); - assertEquals(400, response.getStatusCodeValue()); - - } - - @Test - public void testUnlock() throws ParseException { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS")) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(204, response.getStatusCodeValue()); - } - - @Test - public void testUnlockComplete() throws ParseException { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody().toString(); - assertTrue(body.contains("Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvFilter() { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "not-there"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - //204s cannot have a body - //assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB")); - assertEquals(204, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvSuccess() throws ParseException { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplateNoBody, "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>("", headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); +public class CloudResourcesOrchestrationTest extends BaseTest { + + private String requestJSON = + "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }"; + private static final String path = "/onap/so/infra/cloudResourcesRequests"; + + HttpHeaders headers = new HttpHeaders(); + + @Before + public void setupTestClass() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_CREATED))); + } + + @Test + public void testUnlockFailObjectMapping() { + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody(); + assertTrue(body.contains("Mapping of request to JSON object failed.")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError1() { + String requestJSON = "{\"requestDetails\": null }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid requestDetails is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError2() { + String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid source is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError3() { + String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid requestorId is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testGetInfraActiveRequestNull() { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB")); + assertEquals(400, response.getStatusCodeValue()); + + } + + @Test + public void testUnlock() throws ParseException { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS")) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(204, response.getStatusCodeValue()); + } + + @Test + public void testUnlockComplete() throws ParseException { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody().toString(); + assertTrue(body.contains( + "Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilter() { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "not-there"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + // 204s cannot have a body + // assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB")); + assertEquals(204, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvSuccess() throws ParseException { + wireMockServer + .stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplateNoBody, + "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>("", headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); assertEquals("90c56827-1c78-4827-bc4d-6afcdb37a51f", response.getHeaders().get("X-TransactionID").get(0)); - } - - @Test - public void testGetOperationalEnvFilterSuccess() throws ParseException { - wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody("{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}") - .withBody("["+String.format(getResponseTemplateNoBody, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")+"]") - .withStatus(HttpStatus.SC_OK))); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess"); - builder.queryParam("operationalEnvironmentName", "myVnfOpEnv"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilterSuccess() throws ParseException { + wireMockServer + .stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, + "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody( + "{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}") + .withBody("[" + String.format(getResponseTemplateNoBody, + "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE") + "]") + .withStatus(HttpStatus.SC_OK))); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess"); + builder.queryParam("operationalEnvironmentName", "myVnfOpEnv"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } - - @Test - public void testGetOperationalEnvFilterException1() throws ParseException { - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestId-getOpEnvFilterEx1"); - iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); - iar.setOperationalEnvId("operationalEnvironmentId"); - iar.setOperationalEnvName("operationalEnvName"); - iar.setRequestorId("xxxxxx"); - iar.setRequestBody(""); - iar.setRequestStatus("COMPLETE"); - iar.setRequestAction("TEST"); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>("", headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - assertEquals(500, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvFilterException2() throws ParseException { - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestIdFilterException2"); - iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); - iar.setOperationalEnvId("operationalEnvId"); - iar.setOperationalEnvName("operationalEnvName"); - iar.setRequestorId("xxxxxx"); - iar.setRequestBody(""); - iar.setRequestStatus("COMPLETE"); - iar.setRequestAction("TEST"); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("operationalEnvironmentName", ""); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - - assertEquals(500, response.getStatusCodeValue()); - assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified")); - } + } + + @Test + public void testGetOperationalEnvFilterException1() throws ParseException { + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestId-getOpEnvFilterEx1"); + iar.setRequestScope("requestScope"); + iar.setRequestType("requestType"); + iar.setOperationalEnvId("operationalEnvironmentId"); + iar.setOperationalEnvName("operationalEnvName"); + iar.setRequestorId("xxxxxx"); + iar.setRequestBody(""); + iar.setRequestStatus("COMPLETE"); + iar.setRequestAction("TEST"); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>("", headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + assertEquals(500, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilterException2() throws ParseException { + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestIdFilterException2"); + iar.setRequestScope("requestScope"); + iar.setRequestType("requestType"); + iar.setOperationalEnvId("operationalEnvId"); + iar.setOperationalEnvName("operationalEnvName"); + iar.setRequestorId("xxxxxx"); + iar.setRequestBody(""); + iar.setRequestStatus("COMPLETE"); + iar.setRequestAction("TEST"); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("operationalEnvironmentName", ""); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + + assertEquals(500, response.getStatusCodeValue()); + assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java index 4e5cfaba48..e9237f604e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java @@ -28,13 +28,10 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.Mockito.doNothing; - import java.io.IOException; - import javax.inject.Provider; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Rule; @@ -55,82 +52,82 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.databind.ObjectMapper; -public class ModelDistributionRequestTest extends BaseTest{ +public class ModelDistributionRequestTest extends BaseTest { - private static final String requestJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }"; + private static final String requestJSON = + "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }"; @Rule public ExpectedException thrown = ExpectedException.none(); - @Mock - private Provider<TenantIsolationRunnable> thread; - @InjectMocks - @Spy - private ModelDistributionRequest request = new ModelDistributionRequest(); - @Mock - private TenantIsolationRunnable runnable = new TenantIsolationRunnable(); - - @Before - public void beforeTest() { - Mockito.when(thread.get()).thenReturn(runnable); - } - - @Test - public void testObjectMapperError() throws ApiException{ + @Mock + private Provider<TenantIsolationRunnable> thread; + @InjectMocks + @Spy + private ModelDistributionRequest request = new ModelDistributionRequest(); + @Mock + private TenantIsolationRunnable runnable = new TenantIsolationRunnable(); + + @Before + public void beforeTest() { + Mockito.when(thread.get()).thenReturn(runnable); + } + + @Test + public void testObjectMapperError() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("Mapping of request to JSON object failed")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); request.updateModelDistributionStatus("", null, null); - } - - @Test - public void testParseError1() throws ApiException{ + } + + @Test + public void testParseError1() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("No valid status is specified")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); String requestErrorJSON = "{\"errorReason\": \"Distribution failed in AAI\" }"; request.updateModelDistributionStatus(requestErrorJSON, null, null); - } - - @Test - public void testParseError2() throws ApiException{ + } + + @Test + public void testParseError2() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("No valid errorReason is specified")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); String requestErrorJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\"}"; request.updateModelDistributionStatus(requestErrorJSON, null, null); - } - - @Test - public void testSuccess() throws ApiException{ - doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class), anyString()); - - Response response = request.updateModelDistributionStatus(requestJSON, null, null); - - assertEquals(200, response.getStatus()); - } - - @Test - public void testSuccess_PATCH() throws ApiException, IOException{ - String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa"; - ObjectMapper mapper = new ObjectMapper(); - Distribution distRequest = mapper.readValue(requestJSON, Distribution.class); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path)); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.PATCH, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - - } - + } + + @Test + public void testSuccess() throws ApiException { + doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class), + anyString()); + + Response response = request.updateModelDistributionStatus(requestJSON, null, null); + + assertEquals(200, response.getStatus()); + } + + @Test + public void testSuccess_PATCH() throws ApiException, IOException { + String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa"; + ObjectMapper mapper = new ObjectMapper(); + Distribution distRequest = mapper.readValue(requestJSON, Distribution.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path)); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.PATCH, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java index 426be98486..d983d1eca8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java @@ -22,11 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -34,110 +32,116 @@ import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.tenantisolationbeans.Action; import org.onap.so.exceptions.ValidationException; import org.springframework.test.context.ActiveProfiles; - import com.fasterxml.jackson.databind.ObjectMapper; -public class TenantIsolationRequestTest extends BaseTest{ +public class TenantIsolationRequestTest extends BaseTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void testParseCloudResourceECOMP() throws Exception { + try { + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseCloudResourceVNF() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseCloudResourceVNFInvalid() throws Exception { + expectedException.expect(ValidationException.class); + + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } + + @Test + public void testParseActivateCloudResource() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.activate); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseActivateCloudResourceInvalid() throws Exception { + expectedException.expect(ValidationException.class); + + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.activate); + assertNotNull(request.getRequestId()); + } + + @Test + public void testParseDeactivateCloudResource() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.deactivate); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseDeactivateCloudResourceInvalid() throws Exception { + expectedException.expect(ValidationException.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testParseCloudResourceECOMP() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseCloudResourceVNF() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseCloudResourceVNFInvalid() throws Exception { - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } - - @Test - public void testParseActivateCloudResource() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.activate); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseActivateCloudResourceInvalid() throws Exception{ - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.activate); - assertNotNull(request.getRequestId()); - } - - @Test - public void testParseDeactivateCloudResource() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.deactivate); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseDeactivateCloudResourceInvalid() throws Exception{ - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.deactivate); - assertNotNull(request.getRequestId()); - } + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.deactivate); + assertNotNull(request.getRequestId()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java index ef57fa1a76..34f9c04b82 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java @@ -21,12 +21,10 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.ParseException; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.apihandlerinfra.ApiHandlerApplication; @@ -36,37 +34,37 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; - import com.fasterxml.jackson.databind.ObjectMapper; -public class DmaapOperationalEnvClientTest extends BaseTest{ - - private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; - private static final String operationalEnvironmentId = "28122015552391"; - private static final String operationalEnvironmentName = "OpEnv-name"; - private static final String operationalEnvironmentType = "VNF"; - private static final String tenantContext = "Test"; - private static final String workloadContext = "VNF_E2E-IST"; - private static final String action = "Create"; - @Autowired - private DmaapOperationalEnvClient client; - - @Test - public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException { - String content = this.getJson("ecomp-openv-request.json"); - ObjectMapper mapper = new ObjectMapper(); - CreateEcompOperationEnvironmentBean expected = mapper.readValue(content, CreateEcompOperationEnvironmentBean.class); - - String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType, - tenantContext, workloadContext, action); - - assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual); - } - - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); - } - +public class DmaapOperationalEnvClientTest extends BaseTest { + + private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; + private static final String operationalEnvironmentId = "28122015552391"; + private static final String operationalEnvironmentName = "OpEnv-name"; + private static final String operationalEnvironmentType = "VNF"; + private static final String tenantContext = "Test"; + private static final String workloadContext = "VNF_E2E-IST"; + private static final String action = "Create"; + @Autowired + private DmaapOperationalEnvClient client; + + @Test + public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException { + String content = this.getJson("ecomp-openv-request.json"); + ObjectMapper mapper = new ObjectMapper(); + CreateEcompOperationEnvironmentBean expected = + mapper.readValue(content, CreateEcompOperationEnvironmentBean.class); + + String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + + assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual); + } + + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); + } + } - + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java index 7329f313a5..4263bbdee1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.FileNotFoundException; import java.io.IOException; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.apihandlerinfra.ApiHandlerApplication; @@ -37,15 +35,17 @@ import org.springframework.test.context.junit4.SpringRunner; public class OperationalEnvironmentPublisherTest extends BaseTest { - @Autowired - private OperationalEnvironmentPublisher publisher; - - @Test - public void getProperties() throws FileNotFoundException, IOException { - - assertEquals("B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0", publisher.getAuth()); - assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey()); - assertEquals("test.operationalEnvironmentEvent", publisher.getTopic()); - assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get()); - } + @Autowired + private OperationalEnvironmentPublisher publisher; + + @Test + public void getProperties() throws FileNotFoundException, IOException { + + assertEquals( + "B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0", + publisher.getAuth()); + assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey()); + assertEquals("test.operationalEnvironmentEvent", publisher.getTopic()); + assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java index 3fcfa5dfa8..cb977607ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java @@ -21,50 +21,48 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.text.ParseException; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.tenantisolation.dmaap.CreateEcompOperationEnvironmentBean; - import com.fasterxml.jackson.databind.ObjectMapper; -public class SDCDmaapClientTest extends BaseTest{ - - private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; - - private static final String operationalEnvironmentId = "28122015552391"; - private static final String operationalEnvironmentName = "Operational Environment Name"; - private static final String operationalEnvironmentType = "ECOMP"; - private static final String tenantContext = "TEST"; - private static final String workloadContext = "ECOMP_E2E-IST"; - private static final String action = "Create" ; - - - - @Test - public void verifyasdcCreateoeRequest() throws IOException, ParseException{ - - ObjectMapper mapper = new ObjectMapper(); - - String expected = "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}"; - - - CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean(); - cBean.setOperationalEnvironmentId(operationalEnvironmentId); - cBean.setoperationalEnvironmentName(operationalEnvironmentName); - cBean.setoperationalEnvironmentType(operationalEnvironmentType); - cBean.settenantContext(tenantContext); - cBean.setworkloadContext(workloadContext); - cBean.setaction(action); - - String actual = mapper.writeValueAsString(cBean); - - assertEquals("payloads are equal", expected, actual); - } - - - +public class SDCDmaapClientTest extends BaseTest { + + private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; + + private static final String operationalEnvironmentId = "28122015552391"; + private static final String operationalEnvironmentName = "Operational Environment Name"; + private static final String operationalEnvironmentType = "ECOMP"; + private static final String tenantContext = "TEST"; + private static final String workloadContext = "ECOMP_E2E-IST"; + private static final String action = "Create"; + + + + @Test + public void verifyasdcCreateoeRequest() throws IOException, ParseException { + + ObjectMapper mapper = new ObjectMapper(); + + String expected = + "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}"; + + + CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean(); + cBean.setOperationalEnvironmentId(operationalEnvironmentId); + cBean.setoperationalEnvironmentName(operationalEnvironmentName); + cBean.setoperationalEnvironmentType(operationalEnvironmentType); + cBean.settenantContext(tenantContext); + cBean.setworkloadContext(workloadContext); + cBean.setaction(action); + + String actual = mapper.writeValueAsString(cBean); + + assertEquals("payloads are equal", expected, actual); + } + + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java index 2cb02e9666..8918b015e9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java @@ -20,7 +20,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java index 5ee2eeaeba..7ad55ded48 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java @@ -21,25 +21,24 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class SDCClientCallFailedTest extends BaseTest{ - - @Test - public void testAsdcException() { - SDCClientCallFailed asdc = new SDCClientCallFailed("failed"); - - assertEquals("failed", asdc.getMessage()); - } - - @Test - public void testAsdcExceptionWithCause() { - SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable")); - - assertEquals("failed", asdc.getMessage()); - assertEquals("throwable", asdc.getCause().getMessage()); - } +public class SDCClientCallFailedTest extends BaseTest { + + @Test + public void testAsdcException() { + SDCClientCallFailed asdc = new SDCClientCallFailed("failed"); + + assertEquals("failed", asdc.getMessage()); + } + + @Test + public void testAsdcExceptionWithCause() { + SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable")); + + assertEquals("failed", asdc.getMessage()); + assertEquals("throwable", asdc.getCause().getMessage()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java index f73a194a7b..db5d15a998 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java @@ -22,24 +22,23 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class TenantIsolationExceptionTest extends BaseTest{ - - @Test - public void testTenantIsolation() { - TenantIsolationException exception = new TenantIsolationException(); - - assertNotNull(exception); - } - - @Test - public void testTenantIsolationException() { - TenantIsolationException exception = new TenantIsolationException("exception"); - - assertEquals("Tenant Isolation error: exception", exception.getMessage()); - } +public class TenantIsolationExceptionTest extends BaseTest { + + @Test + public void testTenantIsolation() { + TenantIsolationException exception = new TenantIsolationException(); + + assertNotNull(exception); + } + + @Test + public void testTenantIsolationException() { + TenantIsolationException exception = new TenantIsolationException("exception"); + + assertEquals("Tenant Isolation error: exception", exception.getMessage()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java index 6c5e968835..3a389ce227 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java @@ -33,11 +33,9 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - import java.util.HashMap; import java.util.Map; import java.util.Optional; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -48,100 +46,112 @@ import org.springframework.beans.factory.annotation.Autowired; -public class AAIClientHelperTest extends BaseTest{ - - @Autowired - private AAIClientHelper clientHelper; - - @Test - public void testGetAaiOperationalEnvironmentSuccess() throws Exception { - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - - AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); - Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class); - assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId()); - } - - @Test - public void testUpdateSuccess() { - wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class), any(OperationalEnvironment.class)); - clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv); - - verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testUpdateMapSuccess() { - wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - Map<String, String> payload = new HashMap<String, String>(); - payload.put("tenant-context", "Test"); - payload.put("workload-context", "ECOMPL_PSL"); - payload.put("operational-environment-status", "ACTIVE"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload); - clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload); - - verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testCreateSuccess() { - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setOperationalEnvironmentId("opeEvnId"); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class)); - clientHelper.createOperationalEnvironment(ecompEnv); - - verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testcreateRelationshipSuccess() { - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).createRelationship(anyString(), anyString()); - clientHelper.createRelationship("managingEcomp", "vnfOp"); - - verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp"); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } +public class AAIClientHelperTest extends BaseTest { + + @Autowired + private AAIClientHelper clientHelper; + + @Test + public void testGetAaiOperationalEnvironmentSuccess() throws Exception { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); + Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class); + assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId()); + } + + @Test + public void testUpdateSuccess() { + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class), + any(OperationalEnvironment.class)); + clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv); + + verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testUpdateMapSuccess() { + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + Map<String, String> payload = new HashMap<String, String>(); + payload.put("tenant-context", "Test"); + payload.put("workload-context", "ECOMPL_PSL"); + payload.put("operational-environment-status", "ACTIVE"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload); + clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload); + + verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testCreateSuccess() { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setOperationalEnvironmentId("opeEvnId"); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class)); + clientHelper.createOperationalEnvironment(ecompEnv); + + verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testcreateRelationshipSuccess() { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).createRelationship(anyString(), anyString()); + clientHelper.createRelationship("managingEcomp", "vnfOp"); + + verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp"); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java index 3915fc8928..4a602345d3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; @@ -30,43 +29,43 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestInfo; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters; - import com.fasterxml.jackson.databind.ObjectMapper; -public class AAIClientObjectBuilderTest extends BaseTest{ +public class AAIClientObjectBuilderTest extends BaseTest { - private CloudOrchestrationRequest request; - private ObjectMapper mapper = new ObjectMapper(); - - @Before + private CloudOrchestrationRequest request; + private ObjectMapper mapper = new ObjectMapper(); + + @Before public void testSetUp() { - request = getCloudOrchestrationRequest(); - } + request = getCloudOrchestrationRequest(); + } + + public CloudOrchestrationRequest getCloudOrchestrationRequest() { + CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); + RequestDetails reqDetails = new RequestDetails(); + RequestInfo reqInfo = new RequestInfo(); + RequestParameters reqParams = new RequestParameters(); + reqParams.setTenantContext("TEST"); + reqParams.setWorkloadContext("ECOMP_TEST"); + reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); + reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); + reqDetails.setRequestInfo(reqInfo); + reqDetails.setRequestParameters(reqParams); + cor.setRequestDetails(reqDetails); + return cor; + } - public CloudOrchestrationRequest getCloudOrchestrationRequest() { - CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); - RequestDetails reqDetails = new RequestDetails(); - RequestInfo reqInfo = new RequestInfo(); - RequestParameters reqParams = new RequestParameters(); - reqParams.setTenantContext("TEST"); - reqParams.setWorkloadContext("ECOMP_TEST"); - reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); - reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); - reqDetails.setRequestInfo(reqInfo); - reqDetails.setRequestParameters(reqParams); - cor.setRequestDetails(reqDetails); - return cor; - } - - @Test - public void testGetAaiClientObjectBuilder() throws Exception { - AAIClientObjectBuilder builder = new AAIClientObjectBuilder(); - org.onap.aai.domain.yang.OperationalEnvironment operEnv = builder.buildAAIOperationalEnvironment("Active", request); - assertEquals("TEST", operEnv.getTenantContext()); - assertEquals("ECOMP_TEST", operEnv.getWorkloadContext()); - assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName()); - assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType()); - } + @Test + public void testGetAaiClientObjectBuilder() throws Exception { + AAIClientObjectBuilder builder = new AAIClientObjectBuilder(); + org.onap.aai.domain.yang.OperationalEnvironment operEnv = + builder.buildAAIOperationalEnvironment("Active", request); + assertEquals("TEST", operEnv.getTenantContext()); + assertEquals("ECOMP_TEST", operEnv.getWorkloadContext()); + assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName()); + assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java index 6fda6afc50..800fb37039 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import static org.junit.Assert.assertThat; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -34,112 +33,96 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; - import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -public class ActivateVnfDBHelperTest extends BaseTest{ - - String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; - String requestId = "TEST_requestId"; - String origRequestId = "TEST_requestId"; - - String workloadContext1 = "TEST_workloadContext1"; - String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; - String distributionId1 = "TEST_distributionId1"; - String errorReason = "ABORTED"; - int retryCountThree = 3; - int retryCountZero = 0; - String recoveryActionRetry = "RETRY"; - String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); - String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); - String statusSent = "SENT"; - - OperationalEnvDistributionStatus expectedDistStatus; - OperationalEnvServiceModelStatus expectedServiceModelStatus; - - @Autowired - private ActivateVnfDBHelper dbHelper; - - @Before - public void testSetUp() { - // prepare expected OperationalEnvDistributionStatus object - expectedDistStatus = new OperationalEnvDistributionStatus(); - expectedDistStatus.setDistributionId(distributionId1); - expectedDistStatus.setOperationalEnvId(operationalEnvironmentId); - expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1); - expectedDistStatus.setDistributionIdStatus(statusOk); - expectedDistStatus.setRequestId(requestId); - expectedDistStatus.setDistributionIdErrorReason(""); - - // prepare expected OperationalEnvServiceModelStatus object - expectedServiceModelStatus = new OperationalEnvServiceModelStatus(); - expectedServiceModelStatus.setRequestId(requestId); - expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId); - expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1); - expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk); - expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry); - expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree)); - expectedServiceModelStatus.setWorkloadContext(workloadContext1); - expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - } - - @Test - public void testOperationalEnvDistributionStatusDbMethods() throws Exception { - - // test insert method - OperationalEnvDistributionStatus distStatus1 = - dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId1, - operationalEnvironmentId, - serviceModelVersionId1, - requestId, - statusOk, - ""); - assertThat(distStatus1, sameBeanAs(expectedDistStatus)); - - // prepare updated expected object - OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus; - expectedUpdatedDistStatus.setDistributionIdStatus(statusError); - expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason); - - // test update method - statusOk to statusError - OperationalEnvDistributionStatus distStatus2 = - dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1, - statusError, - errorReason - ); - assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus)); - - } - - @Test - public void testOperationalEnvServiceModelStatusDbMethods() throws Exception { - - // test insert method - OperationalEnvServiceModelStatus serviceModelStatus1 = - dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId, - operationalEnvironmentId, - serviceModelVersionId1, - statusOk, - recoveryActionRetry, - retryCountThree, - workloadContext1, - vnfOperationalEnvironmentId); - assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus)); - - // prepare updated expected object - OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1; - expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError); - expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero)); - - // test update method - update statusOk to statusError & retryCountThree to retryCountZero - OperationalEnvServiceModelStatus serviceModelStatus2 = - dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1, - statusError, - retryCountZero); - assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus)); - - } - +public class ActivateVnfDBHelperTest extends BaseTest { + + String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; + String requestId = "TEST_requestId"; + String origRequestId = "TEST_requestId"; + + String workloadContext1 = "TEST_workloadContext1"; + String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; + String distributionId1 = "TEST_distributionId1"; + String errorReason = "ABORTED"; + int retryCountThree = 3; + int retryCountZero = 0; + String recoveryActionRetry = "RETRY"; + String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); + String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + String statusSent = "SENT"; + + OperationalEnvDistributionStatus expectedDistStatus; + OperationalEnvServiceModelStatus expectedServiceModelStatus; + + @Autowired + private ActivateVnfDBHelper dbHelper; + + @Before + public void testSetUp() { + // prepare expected OperationalEnvDistributionStatus object + expectedDistStatus = new OperationalEnvDistributionStatus(); + expectedDistStatus.setDistributionId(distributionId1); + expectedDistStatus.setOperationalEnvId(operationalEnvironmentId); + expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1); + expectedDistStatus.setDistributionIdStatus(statusOk); + expectedDistStatus.setRequestId(requestId); + expectedDistStatus.setDistributionIdErrorReason(""); + + // prepare expected OperationalEnvServiceModelStatus object + expectedServiceModelStatus = new OperationalEnvServiceModelStatus(); + expectedServiceModelStatus.setRequestId(requestId); + expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId); + expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1); + expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk); + expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry); + expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree)); + expectedServiceModelStatus.setWorkloadContext(workloadContext1); + expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + } + + @Test + public void testOperationalEnvDistributionStatusDbMethods() throws Exception { + + // test insert method + OperationalEnvDistributionStatus distStatus1 = dbHelper.insertRecordToOperationalEnvDistributionStatus( + distributionId1, operationalEnvironmentId, serviceModelVersionId1, requestId, statusOk, ""); + assertThat(distStatus1, sameBeanAs(expectedDistStatus)); + + // prepare updated expected object + OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus; + expectedUpdatedDistStatus.setDistributionIdStatus(statusError); + expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason); + + // test update method - statusOk to statusError + OperationalEnvDistributionStatus distStatus2 = + dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1, statusError, errorReason); + assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus)); + + } + + @Test + public void testOperationalEnvServiceModelStatusDbMethods() throws Exception { + + // test insert method + OperationalEnvServiceModelStatus serviceModelStatus1 = dbHelper.insertRecordToOperationalEnvServiceModelStatus( + requestId, operationalEnvironmentId, serviceModelVersionId1, statusOk, recoveryActionRetry, + retryCountThree, workloadContext1, vnfOperationalEnvironmentId); + assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus)); + + // prepare updated expected object + OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1; + expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError); + expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero)); + + // test update method - update statusOk to statusError & retryCountThree to retryCountZero + OperationalEnvServiceModelStatus serviceModelStatus2 = + dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1, statusError, + retryCountZero); + assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus)); + + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java index 39f5ed834f..063902152c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java @@ -25,7 +25,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; - import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; @@ -34,160 +33,169 @@ import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.springframework.beans.factory.annotation.Autowired; -public class SDCClientHelperTest extends BaseTest{ +public class SDCClientHelperTest extends BaseTest { - String serviceModelVersionId = "TEST_uuid1"; - String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - String workloadContext = "TEST_workloadContext"; + String serviceModelVersionId = "TEST_uuid1"; + String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + String workloadContext = "TEST_workloadContext"; - @Autowired - private SDCClientHelper sdcClientUtils; + @Autowired + private SDCClientHelper sdcClientUtils; - @Test - public void postActivateOperationalEnvironment_Test() throws ApiException { + @Test + public void postActivateOperationalEnvironment_Test() throws ApiException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", "TEST_distributionId"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", "TEST_distributionId"); - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); - JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext); + JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, + operationalEnvironmentId, workloadContext); - assertEquals("202", jsonResponse.get("statusCode")); - assertEquals("Success", jsonResponse.get("message")); + assertEquals("202", jsonResponse.get("statusCode")); + assertEquals("Success", jsonResponse.get("message")); - } + } - @Test - public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException { + @Test + public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException { - // ERROR in asdc response, invalid json object - JSONObject jsonErrorResponse = new JSONObject(); - jsonErrorResponse.put("requestError", ""); + // ERROR in asdc response, invalid json object + JSONObject jsonErrorResponse = new JSONObject(); + jsonErrorResponse.put("requestError", ""); - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST))); - JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext); + JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, + operationalEnvironmentId, workloadContext); - assertEquals("500", jsonResponse.get("statusCode")); - assertEquals("", jsonResponse.get("messageId")); - assertEquals(" Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.", jsonResponse.get("message")); + assertEquals("500", jsonResponse.get("statusCode")); + assertEquals("", jsonResponse.get("messageId")); + assertEquals( + " Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.", + jsonResponse.get("message")); - } + } - @Test - public void buildUriBuilderTest() { + @Test + public void buildUriBuilderTest() { - try { - String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); - assertEquals("http://localhost:" + env.getProperty("wiremock.server.port") + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate", url); + try { + String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); + assertEquals( + "http://localhost:" + env.getProperty("wiremock.server.port") + + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate", + url); - } catch (Exception e) { - fail("Exception caught: " + e.getMessage()); + } catch (Exception e) { + fail("Exception caught: " + e.getMessage()); - } - } + } + } - @Test - public void buildJsonWorkloadContextTest() throws JSONException { + @Test + public void buildJsonWorkloadContextTest() throws JSONException { - String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext); - assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload); + String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext); + assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload); - } + } - @Test - public void enhanceJsonResponseTest_Success() throws JSONException { + @Test + public void enhanceJsonResponseTest_Success() throws JSONException { - // build success response data - JSONObject sdcResponseJsonObj = new JSONObject(); - sdcResponseJsonObj.put("distributionId", "TEST_distributionId"); + // build success response data + JSONObject sdcResponseJsonObj = new JSONObject(); + sdcResponseJsonObj.put("distributionId", "TEST_distributionId"); - int statusCode = 202; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + int statusCode = 202; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("202", sdcResponseJsonObj.getString("statusCode")); - assertEquals("", sdcResponseJsonObj.getString("messageId")); - assertEquals("Success", sdcResponseJsonObj.getString("message")); - assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId")); + assertEquals("202", sdcResponseJsonObj.getString("statusCode")); + assertEquals("", sdcResponseJsonObj.getString("messageId")); + assertEquals("Success", sdcResponseJsonObj.getString("message")); + assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId")); - } + } - @Test - public void enhanceJsonResponseTest_Error() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 409; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 409; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("409", sdcResponseJsonObj.getString("statusCode")); - assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId")); - assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message")); + assertEquals("409", sdcResponseJsonObj.getString("statusCode")); + assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId")); + assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message")); - } + } - @Test - public void enhanceJsonResponseTest_Error_policyException() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error_policyException() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "POL5003"); - jsonMessages.put("text", "Error: Not authorized to use the API."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "POL5003"); + jsonMessages.put("text", "Error: Not authorized to use the API."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 403; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 403; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("403", sdcResponseJsonObj.getString("statusCode")); - assertEquals("POL5003", sdcResponseJsonObj.getString("messageId")); - assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message")); + assertEquals("403", sdcResponseJsonObj.getString("statusCode")); + assertEquals("POL5003", sdcResponseJsonObj.getString("messageId")); + assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message")); - } + } - @Test - public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "POL5003"); - jsonMessages.put("text", "Error: Not authorized to use the API."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("unexpectedResponseTag", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "POL5003"); + jsonMessages.put("text", "Error: Not authorized to use the API."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("unexpectedResponseTag", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 403; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 403; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("500", sdcResponseJsonObj.getString("statusCode")); - assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId")); - assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message")); + assertEquals("500", sdcResponseJsonObj.getString("statusCode")); + assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId")); + assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message")); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java index 4f12afcb71..feebbd49d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java @@ -29,13 +29,10 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.util.ArrayList; import java.util.List; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.json.JSONObject; import org.junit.Before; @@ -57,156 +54,167 @@ import org.onap.so.client.aai.AAIVersion; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class ActivateVnfOperationalEnvironmentTest extends BaseTest{ - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Autowired - private ActivateVnfOperationalEnvironment activateVnf; - @Autowired - private AAIClientHelper clientHelper; - - private final String requestId = "TEST_requestId"; - private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d"; - private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d"; - private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private final String workloadContext = "PVT"; - String recoveryActionRetry = "RETRY"; - private final String serviceModelVersionId = "TEST_serviceModelVersionId"; - int retryCount = 3; - private final String sdcDistributionId = "TEST_distributionId"; - private final String statusSent = "SENT"; - private final ObjectMapper mapper = new ObjectMapper(); - - @Before - public void init(){ - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - - - @Test - public void getAAIOperationalEnvironmentTest() { - - OperationalEnvironment aaiOpEnv; - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED))); - - AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); - aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get(); - assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId()); - assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0).getRelationshipData().get(0).getRelationshipValue()); - assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)); - assertEquals( "EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId).asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId()); - - } - - @Test - public void executionTest() throws Exception { - - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - RequestDetails requestDetails = new RequestDetails(); - RequestParameters requestParameters = new RequestParameters(); - Manifest manifest = new Manifest(); - manifest.setServiceModelList(serviceModelVersionIdList); - requestParameters.setManifest(manifest); - requestParameters.setWorkloadContext(workloadContext); - requestDetails.setRequestParameters(requestParameters); - - request.setOperationalEnvironmentId(vnfOperationalEnvironmentId); - request.setRequestDetails(requestDetails); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - activateVnf.execute(requestId, request); - } - - @Test - public void processActivateSDCRequestTest_202() throws Exception { - - String distributionId = "TEST_distributionId"; - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", distributionId); - - // prepare request detail - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId); - } - - @Test - public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException { - - // ERROR in asdc - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("message", "Failure"); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - //jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorResponse = new JSONObject(); - jsonErrorResponse.put("requestError", jsonServException); - - // prepare request detail - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setRequestStatus("PENDING"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - thrown.expect(ValidateException.class); - - activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId); - } - +public class ActivateVnfOperationalEnvironmentTest extends BaseTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Autowired + private ActivateVnfOperationalEnvironment activateVnf; + @Autowired + private AAIClientHelper clientHelper; + + private final String requestId = "TEST_requestId"; + private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d"; + private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d"; + private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private final String workloadContext = "PVT"; + String recoveryActionRetry = "RETRY"; + private final String serviceModelVersionId = "TEST_serviceModelVersionId"; + int retryCount = 3; + private final String sdcDistributionId = "TEST_distributionId"; + private final String statusSent = "SENT"; + private final ObjectMapper mapper = new ObjectMapper(); + + @Before + public void init() { + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + + @Test + public void getAAIOperationalEnvironmentTest() { + + OperationalEnvironment aaiOpEnv; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); + aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get(); + assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId()); + assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0) + .getRelationshipData().get(0).getRelationshipValue()); + assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)); + assertEquals("EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId) + .asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId()); + + } + + @Test + public void executionTest() throws Exception { + + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + RequestDetails requestDetails = new RequestDetails(); + RequestParameters requestParameters = new RequestParameters(); + Manifest manifest = new Manifest(); + manifest.setServiceModelList(serviceModelVersionIdList); + requestParameters.setManifest(manifest); + requestParameters.setWorkloadContext(workloadContext); + requestDetails.setRequestParameters(requestParameters); + + request.setOperationalEnvironmentId(vnfOperationalEnvironmentId); + request.setRequestDetails(requestDetails); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + activateVnf.execute(requestId, request); + } + + @Test + public void processActivateSDCRequestTest_202() throws Exception { + + String distributionId = "TEST_distributionId"; + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", distributionId); + + // prepare request detail + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, + workloadContext, vnfOperationalEnvironmentId); + } + + @Test + public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException { + + // ERROR in asdc + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("message", "Failure"); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + // jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorResponse = new JSONObject(); + jsonErrorResponse.put("requestError", jsonServException); + + // prepare request detail + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setRequestStatus("PENDING"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + thrown.expect(ValidateException.class); + + activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, + workloadContext, vnfOperationalEnvironmentId); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java index c6a74f3d4e..9100e82beb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java @@ -31,10 +31,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.json.JSONObject; import org.junit.Ignore; @@ -53,606 +51,619 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; import org.springframework.beans.factory.annotation.Autowired; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest{ +public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest { - @Autowired - private ActivateVnfStatusOperationalEnvironment activateVnfStatus; + @Autowired + private ActivateVnfStatusOperationalEnvironment activateVnfStatus; @Rule public ExpectedException thrown = ExpectedException.none(); - private final String requestId = "TEST_requestId"; - private final String requestIdOrig = "TEST_requestIdOrig"; - private final String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; - private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private final String workloadContext = "TEST_workloadContext"; - private final String recoveryActionRetry = "RETRY"; - private final String recoveryActionAbort = "ABORT"; - private final String recoveryActionSkip = "SKIP"; - private final String serviceModelVersionId = "TEST_serviceModelVersionId"; - private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; - private final int retryCountThree = 3; - private final int retryCountTwo = 2; - private final int retryCountZero = 0; - private final String sdcDistributionId1 = "TEST_distributionId1"; - private final String sdcDistributionId = "TEST_distributionId"; - private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString(); - private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); - private final String statusSent = "SENT"; - String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; - - private final ObjectMapper mapper = new ObjectMapper(); - - @Test - public void checkOrUpdateOverallStatusTest_Ok() throws Exception { - - // two entries, both status Ok & retry 0 - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusOk); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId1); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusOk); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - - // overall is success - } - - @Test - public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); + private final String requestId = "TEST_requestId"; + private final String requestIdOrig = "TEST_requestIdOrig"; + private final String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; + private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private final String workloadContext = "TEST_workloadContext"; + private final String recoveryActionRetry = "RETRY"; + private final String recoveryActionAbort = "ABORT"; + private final String recoveryActionSkip = "SKIP"; + private final String serviceModelVersionId = "TEST_serviceModelVersionId"; + private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; + private final int retryCountThree = 3; + private final int retryCountTwo = 2; + private final int retryCountZero = 0; + private final String sdcDistributionId1 = "TEST_distributionId1"; + private final String sdcDistributionId = "TEST_distributionId"; + private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString(); + private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + private final String statusSent = "SENT"; + String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; + + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void checkOrUpdateOverallStatusTest_Ok() throws Exception { + + // two entries, both status Ok & retry 0 + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusOk); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId1); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusOk); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); + + // overall is success + } + + @Test + public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); try { activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - - } - - @Test - public void checkOrUpdateOverallStatusTest_Waiting() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountTwo); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - } - - @Test - public void executionTest_Ok() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusSent); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusSent); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - } - - @Test - public void executionTest_ERROR_Status_And_RETRY() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - - // prepare new distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - distribution.setErrorReason("Unable to process."); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - // prepare sdc return data - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId1); - - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - } - - @Test - public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - + + } + + @Test + public void checkOrUpdateOverallStatusTest_Waiting() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountTwo); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); + } + + @Test + public void executionTest_Ok() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusSent); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusSent); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + } + + @Test + public void executionTest_ERROR_Status_And_RETRY() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare new distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + distribution.setErrorReason("Unable to process."); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + // prepare sdc return data + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId1); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + } + + @Test + public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - - } - - @Test - public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - distribution.setErrorReason("Unable to process."); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - // ERROR in sdc - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("statusCode", "409"); - jsonMessages.put("message", "Undefined Error Message!"); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString()).withStatus(HttpStatus.SC_CONFLICT))); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - try { + + } + + @Test + public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + distribution.setErrorReason("Unable to process."); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + // ERROR in sdc + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("statusCode", "409"); + jsonMessages.put("message", "Undefined Error Message!"); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString()) + .withStatus(HttpStatus.SC_CONFLICT))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Failure calling SDC: statusCode: ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - } - - @Test - public void executionTest_ERROR_Status_And_SKIP() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionSkip); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId,operationalEnvironmentId,serviceModelVersionId); - distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name()); - - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - - } - - @Test - public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionAbort); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(containing("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(containing("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - + } + + @Test + public void executionTest_ERROR_Status_And_SKIP() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionSkip); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId, + operationalEnvironmentId, serviceModelVersionId); + distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name()); + + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + + } + + @Test + public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionAbort); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(containing( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(containing( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e) { - assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); - assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); - assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); - } - - } - - @Test - @Ignore - public void callSDClientForRetryTest_202() throws Exception { - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusSent); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusSent); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId1); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution); - - assertEquals("TEST_distributionId1", jsonResponse.get("distributionId")); - assertEquals("Success", jsonResponse.get("message")); - assertEquals("202", jsonResponse.get("statusCode")); - - } + } catch (ApiException e) { + assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); + assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); + assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); + } + + } + + @Test + @Ignore + public void callSDClientForRetryTest_202() throws Exception { + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusSent); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusSent); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId1); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution); + + assertEquals("TEST_distributionId1", jsonResponse.get("distributionId")); + assertEquals("Success", jsonResponse.get("message")); + assertEquals("202", jsonResponse.get("statusCode")); + + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java index 22993b17cf..3114f91096 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java @@ -29,12 +29,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertThat; - import java.util.UUID; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; @@ -52,90 +49,93 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.springframework.beans.factory.annotation.Autowired; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class CreateEcompOperationalEnvironmentTest extends BaseTest{ - - @Autowired - private CreateEcompOperationalEnvironment createEcompOpEn; - private final ObjectMapper mapper = new ObjectMapper(); +public class CreateEcompOperationalEnvironmentTest extends BaseTest { + + @Autowired + private CreateEcompOperationalEnvironment createEcompOpEn; + private final ObjectMapper mapper = new ObjectMapper(); + + public CloudOrchestrationRequest getCloudOrchestrationRequest() { + CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + RequestDetails reqDetails = new RequestDetails(); + RequestInfo reqInfo = new RequestInfo(); + RequestParameters reqParams = new RequestParameters(); + reqParams.setTenantContext("TEST"); + reqParams.setWorkloadContext("ECOMP_TEST"); + reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); + reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); + reqDetails.setRequestInfo(reqInfo); + reqDetails.setRequestParameters(reqParams); + request.setRequestDetails(reqDetails); + request.setOperationalEnvironmentId("operationalEnvId"); + + return request; + } + + @Test + public void testProcess() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("123"); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/123")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(containing( + "{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + createEcompOpEn.execute("123", getCloudOrchestrationRequest()); + } + + @Test + public void testProcessException() throws JsonProcessingException { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - public CloudOrchestrationRequest getCloudOrchestrationRequest() { - CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - RequestDetails reqDetails = new RequestDetails(); - RequestInfo reqInfo = new RequestInfo(); - RequestParameters reqParams = new RequestParameters(); - reqParams.setTenantContext("TEST"); - reqParams.setWorkloadContext("ECOMP_TEST"); - reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); - reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); - reqDetails.setRequestInfo(reqInfo); - reqDetails.setRequestParameters(reqParams); - request.setRequestDetails(reqDetails); - request.setOperationalEnvironmentId("operationalEnvId"); - - return request; - } - - @Test - public void testProcess() throws ApiException, JsonProcessingException { - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/events/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("123"); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/123")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - createEcompOpEn.execute("123", getCloudOrchestrationRequest()); - } - - @Test - public void testProcessException() throws JsonProcessingException { - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/events/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - InfraActiveRequests iar = new InfraActiveRequests(); String uuid = UUID.randomUUID().toString(); - iar.setRequestId(uuid); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+uuid)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+uuid+ "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); + iar.setRequestId(uuid); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + uuid)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + uuid + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); - try { + try { createEcompOpEn.execute(uuid, getCloudOrchestrationRequest()); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e, sameBeanAs((ApiException) expectedException).ignoring("cause")); } - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java index 59a65676e2..ebed4fa16b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java @@ -28,15 +28,12 @@ import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; - import java.io.File; import java.nio.file.Files; import java.util.List; import java.util.UUID; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -49,142 +46,155 @@ import org.onap.so.client.grm.beans.Property; import org.onap.so.client.grm.beans.ServiceEndPointList; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -public class CreateVnfOperationalEnvironmentTest extends BaseTest{ - - private CloudOrchestrationRequest request; - private ServiceEndPointList serviceEndpoints; - private ServiceEndPointList serviceEndpoints2; - - @Autowired - private CreateVnfOperationalEnvironment createVnfOpEnv; - - @Before - public void testSetUp() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json"); - request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class); - String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json"); - serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class); - String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json"); - serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class); - } - @Test - public void testGetEcompManagingEnvironmentId() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId()); - } - - @Test - public void testGetTenantContext() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("Test", createVnfOpEnv.getTenantContext()); - } - - @Test - public void testGetEnvironmentName() { - createVnfOpEnv.setRequest(request); - List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties(); - assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); - } - - @Test - public void testGetEnvironmentNameEndpointListBeginWithUpperCase() { - createVnfOpEnv.setRequest(request); - List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties(); - assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); - } - - @Test - public void testBuildServiceNameForVnf() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory")); - } - - @Test - public void testGetSearchKey() { - createVnfOpEnv.setRequest(request); - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv)); - } - - public String getFileContentsAsString(String fileName) { - String content = ""; - try { - ClassLoader classLoader = this.getClass().getClassLoader(); - File file = new File(classLoader.getResource(fileName).getFile()); - content = new String(Files.readAllBytes(file.toPath())); - } - catch(Exception e) { - e.printStackTrace(); - System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); - } - return content; - } - - @Test - public void testExecute() throws ApiException, JsonProcessingException { - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - String requestId = UUID.randomUUID().toString(); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - ObjectMapper mapper = new ObjectMapper(); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - createVnfOpEnv.execute(requestId, request); - } - - @Test - public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException { - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - String requestId = UUID.randomUUID().toString(); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - ObjectMapper mapper = new ObjectMapper(); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - createVnfOpEnv.execute(requestId, request); - } +public class CreateVnfOperationalEnvironmentTest extends BaseTest { + + private CloudOrchestrationRequest request; + private ServiceEndPointList serviceEndpoints; + private ServiceEndPointList serviceEndpoints2; + + @Autowired + private CreateVnfOperationalEnvironment createVnfOpEnv; + + @Before + public void testSetUp() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json"); + request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class); + String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json"); + serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class); + String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json"); + serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class); + } + + @Test + public void testGetEcompManagingEnvironmentId() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId()); + } + + @Test + public void testGetTenantContext() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("Test", createVnfOpEnv.getTenantContext()); + } + + @Test + public void testGetEnvironmentName() { + createVnfOpEnv.setRequest(request); + List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties(); + assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); + } + + @Test + public void testGetEnvironmentNameEndpointListBeginWithUpperCase() { + createVnfOpEnv.setRequest(request); + List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties(); + assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); + } + + @Test + public void testBuildServiceNameForVnf() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory")); + } + + @Test + public void testGetSearchKey() { + createVnfOpEnv.setRequest(request); + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv)); + } + + public String getFileContentsAsString(String fileName) { + String content = ""; + try { + ClassLoader classLoader = this.getClass().getClassLoader(); + File file = new File(classLoader.getResource(fileName).getFile()); + content = new String(Files.readAllBytes(file.toPath())); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); + } + return content; + } + + @Test + public void testExecute() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + String requestId = UUID.randomUUID().toString(); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + ObjectMapper mapper = new ObjectMapper(); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + createVnfOpEnv.execute(requestId, request); + } + + @Test + public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + String requestId = UUID.randomUUID().toString(); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + ObjectMapper mapper = new ObjectMapper(); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + createVnfOpEnv.execute(requestId, request); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java index 1e4208c743..16738e9799 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java @@ -30,10 +30,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Rule; @@ -46,129 +44,140 @@ import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; import org.onap.so.client.aai.AAIVersion; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; - import com.fasterxml.jackson.databind.ObjectMapper; -public class DeactivateVnfOperationalEnvironmentTest extends BaseTest{ +public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { @Rule public ExpectedException thrown = ExpectedException.none(); - @Autowired - private DeactivateVnfOperationalEnvironment deactivate; - - private CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff"; - private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe"; - - private ObjectMapper mapper = new ObjectMapper(); - - @Before - public void init(){ - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - @Test - public void testDeactivateOperationalEnvironment() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"ACTIVE\"}"; - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - wireMockServer.stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateInvalidStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"SUCCESS\"}"; - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); + @Autowired + private DeactivateVnfOperationalEnvironment deactivate; + + private CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff"; + private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe"; + + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void init() { + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + @Test + public void testDeactivateOperationalEnvironment() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"ACTIVE\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + deactivate.execute(requestId, request); + } + + @Test + public void testDeactivateInvalidStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"SUCCESS\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: ")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); - + InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateInactiveStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateNullStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"\"}"; - - wireMockServer.stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); + } + + @Test + public void testDeactivateInactiveStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + deactivate.execute(requestId, request); + } + + @Test + public void testDeactivateNullStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("OperationalEnvironmentStatus is null on OperationalEnvironmentId: ")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); deactivate.execute(requestId, request); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java index 8236e6766f..fdc84966e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java @@ -22,12 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.util.List; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.reflection.impl.PojoClassFactory; @@ -39,49 +36,44 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; -public class TenantIsolationBeansTest extends BaseTest{ - - private static final int EXPECTED_CLASS_COUNT = 25; - private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans"; +public class TenantIsolationBeansTest extends BaseTest { + + private static final int EXPECTED_CLASS_COUNT = 25; + private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans"; + + @Test + public void ensureExpectedPojoCount() { + List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + } + + @Test + public void testPojoStructureAndBehavior() { + Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule()) + .with(new SetterTester()).with(new GetterTester()).build(); + + validator.validate(POJO_PACKAGE, new FilterPackageInfo()); + } + + @Test + public void testTenantIsolationToString() { + TenantIsolationRequest request = new TenantIsolationRequest(); + request.setRequestId("requestId"); + request.setRequestScope("scope"); + request.setRequestType("type"); + request.setStartTime("time"); + request.setRequestDetails(new RequestDetails()); + request.setRequestStatus(new RequestStatus()); - @Test - public void ensureExpectedPojoCount() { - List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses( POJO_PACKAGE, - new FilterPackageInfo()); - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); - } + assertNotNull(request.toString()); + } - @Test - public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - .with(new GetterMustExistRule()) - .with(new SetterMustExistRule()) - .with(new SetterTester()) - .with(new GetterTester()) - .build(); + @Test + public void testRequestListToString() { + RequestList list = new RequestList(); + list.setRequest(new Request()); + list.setRequestStatus(new RequestStatus()); - validator.validate(POJO_PACKAGE, new FilterPackageInfo()); - } - - @Test - public void testTenantIsolationToString() { - TenantIsolationRequest request = new TenantIsolationRequest(); - request.setRequestId("requestId"); - request.setRequestScope("scope"); - request.setRequestType("type"); - request.setStartTime("time"); - request.setRequestDetails(new RequestDetails()); - request.setRequestStatus(new RequestStatus()); - - assertNotNull(request.toString()); - } - - @Test - public void testRequestListToString() { - RequestList list = new RequestList(); - list.setRequest(new Request()); - list.setRequestStatus(new RequestStatus()); - - assertNotNull(list.toString()); - } + assertNotNull(list.toString()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java index 90c994fce0..0ea35a5b8c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java @@ -21,34 +21,32 @@ package org.onap.so.apihandlerinfra.validation; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Test; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class CustomWorkflowValidationTest extends BaseTest{ +public class CustomWorkflowValidationTest extends BaseTest { + + @Test + public void testCustomWorkflowValidation() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.inPlaceSoftwareUpdate, 1, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vnf"); + + CustomWorkflowValidation validation = new CustomWorkflowValidation(); + validation.validate(info); - @Test - public void testCustomWorkflowValidation() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.inPlaceSoftwareUpdate, - 1, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vnf"); - - CustomWorkflowValidation validation = new CustomWorkflowValidation(); - validation.validate(info); - - assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic"); - } + assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java index 02fd7a1aca..54da0baa92 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java @@ -21,35 +21,33 @@ package org.onap.so.apihandlerinfra.validation; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Test; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class RelatedInstancesValidationTest extends BaseTest{ +public class RelatedInstancesValidationTest extends BaseTest { + + @Test + public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vnf"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + validation.validate(info); - @Test - public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vnf"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); - RelatedInstancesValidation validation = new RelatedInstancesValidation(); - validation.validate(info); - - assertEquals(info.getVnfType(), "Test/name"); - } + assertEquals(info.getVnfType(), "Test/name"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java index bd9b95dc12..4f5209d8b4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java @@ -22,148 +22,153 @@ package org.onap.so.apihandlerinfra.validation; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Test; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class RequestParametersValidationTest extends BaseTest{ +public class RequestParametersValidationTest extends BaseTest { + + @Test + public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithNoALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithFalseALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithNoALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithTrueALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } - @Test - public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithNoALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, true, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 3, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithFalseALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithNoALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithTrueALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, true, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithReqVersionBelow4() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 3, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } + @Test + public void testServiceWithReqVersionBelow4() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java index c1c4915672..ba02254ad8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -32,78 +31,94 @@ import org.onap.so.apihandlerinfra.Action; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class UserParamsValidationTest{ - - UserParamsValidation validation = new UserParamsValidation(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public ValidationInformation setupValidationInformation(String path) throws IOException{ - String jsonInput = new String(Files.readAllBytes(Paths.get(path))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters()); - for(Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()){ - ObjectMapper obj = new ObjectMapper(); - String input = obj.writeValueAsString(params.get("service")); - Service validate = obj.readValue(input, Service.class); - info.setUserParams(validate); - break; - } - info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); - return info; - } - - @Test - public void validateModelTypeExceptionTest() throws IOException, ValidationException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid modelType in userParams service modelInfo is specified"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json")); - } - @Test - public void validateInstanceNameExceptionTest() throws IOException, ValidationException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json")); - } - @Test - public void validateModelTypeTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json")); - } - @Test - public void validateModelInvariantIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json")); - } - @Test - public void validateModelVersionIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json")); - } - @Test - public void validateModelNameTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json")); - } - @Test - public void validateModelVersionTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json")); - } - @Test - public void validateModelCustomizationIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json")); - } -}
\ No newline at end of file +public class UserParamsValidationTest { + + UserParamsValidation validation = new UserParamsValidation(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public ValidationInformation setupValidationInformation(String path) throws IOException { + String jsonInput = new String(Files.readAllBytes(Paths.get(path))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, + sir.getRequestDetails().getRequestParameters()); + for (Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()) { + ObjectMapper obj = new ObjectMapper(); + String input = obj.writeValueAsString(params.get("service")); + Service validate = obj.readValue(input, Service.class); + info.setUserParams(validate); + break; + } + info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); + return info; + } + + @Test + public void validateModelTypeExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelType in userParams service modelInfo is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json")); + } + + @Test + public void validateInstanceNameExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json")); + } + + @Test + public void validateModelTypeTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json")); + } + + @Test + public void validateModelInvariantIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json")); + } + + @Test + public void validateModelVersionIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json")); + } + + @Test + public void validateModelNameTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json")); + } + + @Test + public void validateModelVersionTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json")); + } + + @Test + public void validateModelCustomizationIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage( + "modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json")); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java index c469a56e48..e208a38f47 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.workflowspecificationbeans; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; - import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; @@ -30,11 +29,11 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; -public class WorkflowSpecificationBeansTest extends BaseTest{ - @Test - public void validateGettersAndSetters() { - Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) - .with(new SetterTester(), new GetterTester()).build(); - validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); - } +public class WorkflowSpecificationBeansTest extends BaseTest { + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java index 580252ae73..f178a3c0cb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java @@ -30,14 +30,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - import java.io.File; import java.nio.file.Files; import java.util.List; import java.util.Map; - import javax.ws.rs.core.MediaType; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -51,119 +48,110 @@ import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest; import org.onap.so.client.grm.beans.ServiceEndPointRequest; import org.onap.so.client.grm.exceptions.GRMClientCallFailed; import org.slf4j.MDC; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class GRMClientTest extends BaseTest{ - - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static final String uuidRegex = "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$"; - - @BeforeClass - public static void setUp() throws Exception { - System.setProperty("mso.config.path", "src/test/resources"); - } - - @Test - public void testFind() throws Exception { +public class GRMClientTest extends BaseTest { + + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String uuidRegex = + "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$"; + + @BeforeClass + public static void setUp() throws Exception { + System.setProperty("mso.config.path", "src/test/resources"); + } + + @Test + public void testFind() throws Exception { TestAppender.events.clear(); - String endpoints = getFileContentsAsString("__files/grm/endpoints.json"); - wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(endpoints))); - - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test"); - GRMClient client = new GRMClient(); - ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - List<ServiceEndPoint> list = sel.getServiceEndPointList(); - assertEquals(3, list.size()); - - boolean foundInvoke = false; - boolean foundInvokeReturn = false; - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + String endpoints = getFileContentsAsString("__files/grm/endpoints.json"); + wireMockServer + .stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody(endpoints))); + + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test"); + GRMClient client = new GRMClient(); + ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); + List<ServiceEndPoint> list = sel.getServiceEndPointList(); + assertEquals(3, list.size()); + + boolean foundInvoke = false; + boolean foundInvokeReturn = false; + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("GRM",mdc.get("TargetEntity")); - assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvoke=true; - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("INVOKE_RETURN")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("GRM", mdc.get("TargetEntity")); + assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + foundInvoke = true; + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE_RETURN")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvokeReturn=true; + assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); + assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + foundInvokeReturn = true; } - - if(!foundInvoke) + + if (!foundInvoke) fail("INVOKE Marker not found"); - - if(!foundInvokeReturn) + + if (!foundInvokeReturn) fail("INVOKE RETURN Marker not found"); - - wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) + + wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) .withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); + .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) + .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); TestAppender.events.clear(); - } - - @Test - public void testFindFail() throws Exception { - wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(400) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(""))); - - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - } - - @Test - public void testAddFail() throws Exception { - wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody("test"))); - ServiceEndPointRequest request = new ServiceEndPointRequest(); - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.addServiceEndPoint(request); - } - - @Test - public void testBuildServiceEndPointLookupRequest() { - GRMClient client = new GRMClient(); - ServiceEndPointLookupRequest request = client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV"); - assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName()); - assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor())); - assertEquals("DEV", request.getEnv()); - - } - - protected String getFileContentsAsString(String fileName) { - String content = ""; - try { - ClassLoader classLoader = this.getClass().getClassLoader(); - File file = new File(classLoader.getResource(fileName).getFile()); - content = new String(Files.readAllBytes(file.toPath())); - } - catch(Exception e) { - e.printStackTrace(); - System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); - } - return content; - } + } + + @Test + public void testFindFail() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn( + aResponse().withStatus(400).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody(""))); + + GRMClient client = new GRMClient(); + thrown.expect(GRMClientCallFailed.class); + client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); + } + + @Test + public void testAddFail() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withStatus(404).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody("test"))); + ServiceEndPointRequest request = new ServiceEndPointRequest(); + GRMClient client = new GRMClient(); + thrown.expect(GRMClientCallFailed.class); + client.addServiceEndPoint(request); + } + + @Test + public void testBuildServiceEndPointLookupRequest() { + GRMClient client = new GRMClient(); + ServiceEndPointLookupRequest request = + client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV"); + assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName()); + assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor())); + assertEquals("DEV", request.getEnv()); + + } + + protected String getFileContentsAsString(String fileName) { + String content = ""; + try { + ClassLoader classLoader = this.getClass().getClassLoader(); + File file = new File(classLoader.getResource(fileName).getFile()); + content = new String(Files.readAllBytes(file.toPath())); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); + } + return content; + } } |