diff options
author | Kotagiri, Ramprasad (rp5662) <rp5662@att.com> | 2020-08-07 15:54:10 -0400 |
---|---|---|
committer | Kotagiri, Ramprasad (rp5662) <rp5662@att.com> | 2020-08-12 12:38:26 -0400 |
commit | 09762dc92a06fb885f7055796db390a3a1baa535 (patch) | |
tree | e377c24a2cccb0a7d90b7b8560a7d8eef048a610 /ccsdk-app-common/src/test/java/org | |
parent | f796af3a840d0fd9319e3dfe45ef0e548cd90171 (diff) |
CCSDK DCAE dashboard feature changes
Issue-ID: DCAEGEN2-1857
Issue-ID: DCAEGEN2-2074
Issue-ID: DCAEGEN2-2364
Change-Id: I97f5ec4599512ed848136971b11d4c2a137a4999
Signed-off-by: Kotagiri, Ramprasad (rp5662) <rp5662@att.com>
Diffstat (limited to 'ccsdk-app-common/src/test/java/org')
11 files changed, 2299 insertions, 1916 deletions
diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java new file mode 100644 index 0000000..3c33bda --- /dev/null +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/api/controller/NbApiControllerTest.java @@ -0,0 +1,818 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.ccsdk.api.controller; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.core.MockUser; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.exceptions.BadRequestException; +import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; +import org.onap.ccsdk.dashboard.exceptions.DownstreamException; +import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; +import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; +import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; +import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; +import org.onap.ccsdk.dashboard.model.inventory.Service; +import org.onap.ccsdk.dashboard.model.inventory.ServiceList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceType; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; +import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.ConsulClient; +import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.util.CacheManager; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; + +@RunWith(PowerMockRunner.class) +public class NbApiControllerTest extends MockitoTestSuite { + + @Mock + InventoryClient inventoryClient; + + @Mock + DeploymentHandlerClient deploymentHandlerClient; + + @Mock + CloudifyClient cfyClient; + + @Mock + ConsulClient consulClient; + + @Mock + ServletUriComponentsBuilder uriBuilder; + + @InjectMocks + NbApiController subject = new NbApiController(); + + private HttpStatusCodeException httpException = + new HttpServerErrorException(HttpStatus.BAD_GATEWAY); + + protected final ObjectMapper objectMapper = new ObjectMapper(); + + HttpServletRequest mockedRequest; + HttpServletResponse mockedResponse; + + MockUser mockUser = new MockUser(); + ServiceList deplList = null; + Service deplItem = null; + + + ServiceTypeSummary bpItem, bpItem2 = null; + ServiceTypeSummaryList bpList, bpList2 = null; + ServiceType bpItemFull = null; + ServiceTypeList bpItemFullList = null; + ServiceTypeRequest bpUploadItem = null; + + BadRequestException badReqError; + ServiceAlreadyExistsException srvcExistError; + ServerErrorException serverError; + DownstreamException downStrmError; + JsonProcessingException jsonError; + DeploymentNotFoundException notFoundError; + private ServiceTypeNotFoundException serviceTypeException = + new ServiceTypeNotFoundException("Invalid blueprint"); + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + objectMapper.registerModule(new Jdk8Module()); + getExpectedDeployments(); + getExpectedBueprints(); + createBpUploadItem(); + mockedRequest = getMockedRequest(); + mockedResponse = getMockedResponse(); + badReqError = new BadRequestException("bad request"); + srvcExistError = new ServiceAlreadyExistsException("service already exists"); + serverError = new ServerErrorException("Error occured in server"); + downStrmError = new DownstreamException("error occured in downstream"); + notFoundError = new DeploymentNotFoundException("item not found"); + CacheManager testCache = new CacheManager(); + subject.setCacheManager(testCache); + User user = mockUser.mockUser(); + user.setLoginId("tester"); + StringBuffer urlBuff = new StringBuffer(); + urlBuff.append("http://orcl.com"); + //Mockito.when(mockedRequest.getRemoteUser()).thenReturn("tester"); + Mockito.when(mockedRequest.getRequestURL()).thenReturn(urlBuff); + } + + public void getExpectedDeployments() + throws JsonParseException, JsonMappingException, IOException { + + deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, + "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); + Collection<Service> items = new ArrayList<Service>(); + items.add(deplItem); + + String pageLinks = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); + int totalCount = 1; + deplList = new ServiceList(items, totalCount, paginationLinks); + + } + + public void getExpectedBueprints() + throws JsonParseException, JsonMappingException, IOException { + + /*bpItem = new ServiceTypeSummary.Builder().application("DCAE").component("dcae"). + typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build();*/ + + bpItem = new ServiceTypeSummary("xyz1730", "xyz1730-helm-1905", 1905, "DCAE", "dcae", "123-456-321", + "342343", true); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "DCAE", "dcae", "123-456-789", + "342343", true); + bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + "tosca_definitions_version: cloudify_dsl_1_3", "", "DCAE", "dcae").build(); + + Collection<ServiceTypeSummary> items = new ArrayList<ServiceTypeSummary>(); + items.add(bpItem); + + Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); + items2.add(bpItem2); + + String pageLinks2 = + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + ServiceTypeSummaryList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks2, ServiceTypeSummaryList.PaginationLinks.class); + int totalCount = 1; + bpList = new ServiceTypeSummaryList(items, totalCount, paginationLinks); + bpList2 = new ServiceTypeSummaryList(items2, totalCount, paginationLinks); + + } + + public void createBpUploadItem() { + bpUploadItem = ServiceTypeRequest.from(bpItemFull); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public final void testCreateBlueprint() throws Exception { + String bpTemplate = "tosca_definitions_version: cloudify_dsl_1_3"; + ServiceTypeUploadRequest bpUploadReq = + new ServiceTypeUploadRequest("dcae_user", "mod1", 2008, bpTemplate, "DCAE", "dcae"); + + when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) + .thenThrow(BlueprintParseException.class).thenThrow(httpException) + .thenThrow(Exception.class).thenReturn(bpItemFull); + + //when(mockedRequest.getRequestURI()).thenReturn("https://invt-svc:8080/dcae-service-types"); + String actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual.contains("error")); + actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual.contains("error")); + actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual.contains("error")); + actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual.contains("xyz")); + } + + @Test + public final void testCreateBlueprint_badReq() throws Exception { + String bpTemplate = "tosca_definitions_version: cloudify_dsl_1_3"; + ServiceTypeUploadRequest bpUploadReq = + new ServiceTypeUploadRequest("dcae_user", "mod1", 2008, bpTemplate, "DCAE", ""); + + when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) + .thenThrow(BlueprintParseException.class).thenThrow(httpException) + .thenThrow(Exception.class).thenReturn(null); + + String actual = subject.createBlueprint(mockedRequest, mockedResponse, bpUploadReq, uriBuilder); + assertTrue(actual.contains("error")); + } + + @Test + public final void testQueryBlueprint() throws Exception { + + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); + when(inventoryClient.getServiceType(Mockito.any())).thenReturn(optionBp).thenThrow(Exception.class); + + String actual = subject.queryBlueprint("123-343", mockedRequest, mockedResponse, uriBuilder); + assertTrue(actual.contains("xyz")); + + actual = subject.queryBlueprint("123-343", mockedRequest, mockedResponse, uriBuilder); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetTenants() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + + Mockito.when(cfyClient.getTenants()).thenReturn(sampleData); + + String tenantStr = subject.getTenants(mockedRequest); + assertTrue(tenantStr.contains("dyh1b")); + } + + @Test + public final void testGetBlueprintsByPage() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + String filterStr = "{\"owner\": \"xyz1730\", \"name\": \"xyz1730-helm-1905\", \"id\": \"123\"}"; + + mockedRequest.addParameter("filters", filterStr); + mockedRequest.addParameter("sort", "name"); + + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); + String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("error")); + } + + @Test + public final void testGetBlueprintsByPage_sortByOwner() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sort", "owner"); + + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); + String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("error")); + } + + @Test + public final void testGetBlueprintsByPage_sortByTypeId() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sort", "typeId"); + + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); + String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("error")); + } + + @Test + public final void testGetBlueprintsByPage_sortByCreated() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sort", "created"); + + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); + String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("error")); + } + + @Test + public final void testGetBlueprintsByPage_sortByVersion() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("sort", "typeVersion"); + + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1).thenThrow(Exception.class); + String result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("xyz")); + + result = subject.getBlueprintsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(result.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetDeployment() { + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + when(cfyClient.getDeployment(Mockito.any())).thenReturn(cldDeplList).thenThrow(Exception.class); + + String actual = subject.getDeployment("id1", mockedRequest); + assertTrue(actual.contains("id1")); + + actual = subject.getDeployment("id1", mockedRequest); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetDeploymentsByPage() throws Exception { + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + when(cfyClient.getDeploymentsWithFilter(Mockito.any())).thenReturn(items).thenThrow(Exception.class); + + String actual = subject.getDeploymentsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(actual.contains("id1")); + + actual = subject.getDeploymentsByPage(mockedRequest, 1, 1, uriBuilder, mockedResponse); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetDeploymentInputs() throws Exception { + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + when(cfyClient.getDeploymentInputs(Mockito.any(), Mockito.any())).thenReturn(cldDeplList).thenThrow(httpException).thenThrow(Exception.class); + + String actual = subject.getDeploymentInputs("dep_id", "tenant1", mockedRequest); + assertTrue(actual.contains("id1")); + + actual = subject.getDeploymentInputs("dep_id", "tenant1", mockedRequest); + assertTrue(actual.contains("error")); + + actual = subject.getDeploymentInputs("dep_id", "tenant1", mockedRequest); + assertTrue(actual.contains("error")); + + } + + @Test + public final void testGetServicesForType() throws Exception { + String testTypeIds = "44234234"; + ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); + Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); + expectedSrvcIds.add(expectedSrvc); + ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); + + when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(expectedSrvcRefList); + String actual = subject.getServicesForType(mockedRequest, testTypeIds); + assertTrue(actual.contains(testTypeIds)); + } + + @SuppressWarnings("unchecked") + @Test + public final void testCreateDeployment() throws Exception { + Map<String, Object> inputs = new HashMap<>(); + inputs.put("key1", "value1"); + inputs.put("key2", "value2"); + inputs.put("key3", "value3"); + inputs.put("key4", 100); + + DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", + "xyz1731-helm-1906", 1906, "blueprintId", inputs, "tenant1", + null, true, true, true, false, true, false); + + DeploymentInput deployInput2 = new DeploymentInput("component1", "tag1", + "xyz1731-helm-1906", 1906, null, inputs, "tenant1", + null, true, true, true, false, true, false); + + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); + DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); + + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream1); + +/* String actualResp0 = subject.createDeployment(mockedRequest, mockedResponse, deployInput2); + assertTrue(actualResp0.contains("error"));*/ + + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); + Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); + + StringBuffer expectedStrBuff = new StringBuffer(); + expectedStrBuff.append("http://oom.s2.com"); + when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); + + when(deploymentHandlerClient.putDeployment(Matchers.anyString(), Matchers.anyString(), + Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenReturn(expectResp) + .thenThrow(badReqError) + .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) + .thenThrow(Exception.class); + + String actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("component1")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput2); + assertTrue(actualResp.contains("component1")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("error")); + + actualResp = subject.createDeployment(mockedRequest, mockedResponse, deployInput1); + assertTrue(actualResp.contains("error")); + + } + + @Test + public final void testGetExecutionByDeploymentId() throws Exception { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) + .thenReturn(cloudifyExecutionList).thenThrow(httpException).thenThrow(Exception.class);; + + String actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("execution_id1")); + + actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + + actual = subject.getExecutionByDeploymentId("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + + } + + @Test + public final void testGetServiceHealthByDeploymentId() throws Exception { + String[] svcTags = {"cfytenantname=onap"}; + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); + + ConsulDeploymentHealth cnslDeployHlth = + new ConsulDeploymentHealth.Builder(consulSrvcHlth).build(); + + when(consulClient.getServiceHealthByDeploymentId(Mockito.any())).thenReturn(cnslDeployHlth) + .thenThrow(httpException).thenThrow(Exception.class); + + String actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); + assertTrue(actual.contains("cjlvmcnsl00")); + + actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); + assertTrue(actual.contains("error")); + + actual = subject.getServiceHealthByDeploymentId("deploymentId", mockedRequest); + assertTrue(actual.contains("error")); + } + + @Test + public final void testDeleteBlueprint() throws Exception { + //String expected = "{\"202\": \"OK\"}"; + String expected = "{\"204\": \"Blueprint deleted\"}"; + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); + deplForBp.clear(); + Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) + .thenReturn(deplForBp); + + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); + Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); + + List<ServiceRef> srvcRefList = new ArrayList<>(); + srvcRefList.clear(); + int itemCnt = 0; + ServiceRefList mockSvcRefList = new ServiceRefList(srvcRefList, itemCnt); + + Mockito.when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(mockSvcRefList); + + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) + .deleteServiceType(Matchers.anyString()); + + String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + assertEquals(expected, actual); + + actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + assertTrue(actual.contains("error")); + + actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + assertTrue(actual.contains("error")); + } + + @Test + public final void testDeleteBlueprint_withDepl() throws Exception { + CloudifyDeployedTenant mockCfyDeplTen = + new CloudifyDeployedTenant("id1", "tenant", "45435435", "54543534"); + + Optional<ServiceType> optionBp = Optional.ofNullable(bpItemFull); + Mockito.when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(optionBp); + + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); + deplForBp.add(mockCfyDeplTen); + Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) + .thenReturn(deplForBp); + + String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse, uriBuilder); + assertTrue(actual.contains("error")); + } + + @Test + public final void testDeleteDeployment() throws Exception { + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "dcae_dep_id", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + Mockito.when(cfyClient.getDeployment(Matchers.anyString(), Matchers.anyString())).thenReturn(cldDeplList); + + doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) + .doThrow(notFoundError).doThrow(Exception.class).when(deploymentHandlerClient) + .deleteDeployment(Matchers.anyString(), Matchers.anyString()); + + String actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("dcae_dep_id")); + + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteDeployment("dcae_dep_id", mockedRequest, "tenant1", mockedResponse); + assertTrue(actual.contains("error")); + + } + + @SuppressWarnings("unchecked") + @Test + public void testCancelExecution() throws Exception { + List<String> tenants = new ArrayList<String>(); + tenants.add("tenant1"); + + HttpHeaders httpHeader = new HttpHeaders(); + httpHeader.put("tenant", tenants); + + CloudifyExecution cfyExecObj = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + when(cfyClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + + String actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("execution_id1")); + + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + + actualResult = + subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); + assertTrue(actualResult.contains("error")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testModifyDeployment() throws Exception { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + Map<String, Object> params = new HashMap<String, Object>(); + params.put("tenant", "tenant1"); + params.put("workflow", "upgrade"); + + CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", + "upgrade", false, false, "tenant1", params); + + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + when(cfyClient.getNodeInstanceId(Mockito.any(), Mockito.any())).thenReturn(cfyNodeInstList); + + String secretTokenStr = + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + CloudifySecret secretData = null; + try { + secretData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); + } catch (Exception e) { + + } + when(cfyClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(secretData); + when(cfyClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) + .thenReturn(cldExecution).thenThrow(Exception.class).thenThrow(httpException); + + String inputParamStr = "{\"tenant\": \"tenant1\", \"workflow\":\"upgrade\"}"; + + InputStream is1 = new ByteArrayInputStream(inputParamStr.getBytes()); + String actualResult = subject.modifyDeployment("depId", mockedRequest, is1); + assertTrue(actualResult.contains("execution_id1")); + + InputStream is2 = new ByteArrayInputStream(inputParamStr.getBytes()); + actualResult = subject.modifyDeployment("depId", mockedRequest, is2); + assertTrue(actualResult.contains("error")); + + InputStream is3 = new ByteArrayInputStream(inputParamStr.getBytes()); + actualResult = subject.modifyDeployment("depId", mockedRequest, is3); + assertTrue(actualResult.contains("error")); + + } + +} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java index d6e1fb0..d88e530 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CloudifyControllerTest.java @@ -22,16 +22,22 @@ package org.onap.ccsdk.dashboard.controller; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; @@ -39,39 +45,51 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.core.MockUser; import org.onap.ccsdk.dashboard.core.MockitoTestSuite; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployment; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; -import org.onap.ccsdk.dashboard.model.CloudifyEvent; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifyTenant; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentExt; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentHelm; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEvent; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstance; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPlugin; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPluginList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; +import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; +import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; import org.onap.ccsdk.dashboard.rest.CloudifyClient; +import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.util.CacheManager; import org.onap.portalsdk.core.web.support.UserUtils; +import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +@RunWith(PowerMockRunner.class) public class CloudifyControllerTest extends MockitoTestSuite { @Mock private CloudifyClient restClient; + + @Mock + private InventoryClient invClient; @InjectMocks private CloudifyController subject = new CloudifyController(); @@ -93,6 +111,8 @@ public class CloudifyControllerTest extends MockitoTestSuite { MockitoAnnotations.initMocks(this); objectMapper.registerModule(new Jdk8Module()); httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); + CacheManager testCache = new CacheManager(); + subject.setCacheManager(testCache); } @SuppressWarnings("unchecked") @@ -125,6 +145,409 @@ public class CloudifyControllerTest extends MockitoTestSuite { assertTrue(tenantStr.contains("error")); } + @Test + public final void testGetAllServiceNames() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + //mockedRequest.addParameter("searchBy", "xyz"); + mockedRequest.addParameter("sortBy", "owner"); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + Mockito.when(restClient.getDeployments( + Mockito.any(),Mockito.anyInt(), Mockito.anyInt(), Mockito.anyBoolean())) + .thenReturn(items); + + String actual = subject.getAllServiceNames(mockedRequest); + assertTrue(actual.contains("id1")); + } + @Test + public final void testGetDeploymentsByPage() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "tenant:default_tenant;cache:false;serviceRef:id1"); + mockedRequest.addParameter("sortBy", "owner"); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + Mockito.when(restClient.getDeployments( + Mockito.any(),Mockito.anyInt(), Mockito.anyInt(), Mockito.anyBoolean(), Mockito.anyBoolean())) + .thenReturn(items); + List<CloudifyDeploymentExt> cfyDepExList = + new ArrayList<CloudifyDeploymentExt>(); + List<CloudifyDeploymentHelm> cfyDeplHelmList = + new ArrayList<CloudifyDeploymentHelm>(); + + Mockito.when(restClient.updateWorkflowStatus(Mockito.any())). + thenReturn(cfyDepExList); + Mockito.when(restClient.updateHelmInfo(Mockito.any())). + thenReturn(cfyDeplHelmList); + + String actual = subject.getDeploymentsByPage(mockedRequest); + assertTrue(actual.contains("id1")); + } + + @Test + public final void testViewBlueprintContentById() throws Exception { + byte[] result = "sample blueprint yaml content".getBytes(); + + when(restClient.viewBlueprint(Mockito.any(), Mockito.any())).thenReturn(result); + + byte[] actual = subject.viewBlueprintContentById("id", "tenant", mockedRequest); + assertArrayEquals(result, actual); + } + + @Test + public final void testGetDepCount() throws Exception { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + //mockedRequest.addParameter("searchBy", "xyz"); + mockedRequest.addParameter("sortBy", "owner"); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + CloudifyDeployment cldDepl = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id1", null, null, null, null, null, null, null, "tenant1"); + + List<CloudifyDeployment> items = new ArrayList<CloudifyDeployment>(); + items.add(cldDepl); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeplList = new CloudifyDeploymentList(items, metadata); + + Mockito.when(restClient.getDeploymentsWithFilter(Mockito.any())) + .thenReturn(items); + + String actual = subject.getDepCount(mockedRequest); + assertTrue(actual.contains("items")); + } + + @Test + public final void testGetPluginCount() throws JsonProcessingException { + CloudifyPlugin sampleData = + new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); + + List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); + cfyPlugins.add(sampleData); + + CloudifyPluginList.Metadata.Pagination pageObj = + new CloudifyPluginList.Metadata.Pagination(1, 0, 1); + CloudifyPluginList.Metadata metadata = new CloudifyPluginList.Metadata(pageObj); + + CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); + + when(restClient.getPlugins()).thenReturn(cfyPluginList); + String actual = subject.getPluginCount(mockedRequest); + assertTrue(actual.contains("1")); + } + + @Test + public final void testDeleteBlueprint() throws Exception { + String json = "{\"202\": \"OK\"}"; + + doNothing().doThrow(httpException).doThrow(Exception.class).when(restClient).deleteBlueprint(Mockito.any(), Mockito.any()); + + String actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); + assertTrue(actual.equals(json)); + + actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + + actual = subject.deleteBlueprint("id", "tenant", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetDeploymentsForType() throws Exception { + String[] testTypeIds = {"44234234"}; + ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); + Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); + expectedSrvcIds.add(expectedSrvc); + ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); + + CloudifyDeployedTenant cfyDepTen = + new CloudifyDeployedTenant("id", "tenant_name", "created_at", "updated_at"); + + List<CloudifyDeployedTenant> cfyDeplTenList = new ArrayList<>(); + cfyDeplTenList.add(cfyDepTen); + + when(restClient.getDeploymentForBlueprint(Mockito.any())).thenReturn(cfyDeplTenList); + + when(invClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(expectedSrvcRefList); + String actual = subject.getDeploymentsForType(mockedRequest, testTypeIds); + assertTrue(actual.contains(testTypeIds[0])); + } + + @Test + @Ignore + public final void testCacheOwnerDeployMap() { + + } + + @Test + public final void testGetExecutionsPerTenant() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList tenantData = null; + try { + tenantData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(restClient.getTenants()).thenReturn(tenantData); + + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) + .thenReturn(cloudifyExecutionList).thenReturn(cloudifyExecutionList) + .thenReturn(cloudifyExecutionList); + + String actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "failed"); + assertFalse(actual.contains("execution_id1")); + actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "successful"); + assertTrue(actual.contains("execution_id1")); + actual = subject.getExecutionsPerTenant(mockedRequest, null, "successful"); + assertTrue(actual.contains("execution_id1")); + } + + @Test + public final void testGetExecutionsPerTenant_error() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList tenantData = null; + try { + tenantData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(restClient.getTenants()).thenReturn(tenantData); + + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) + .thenThrow(Exception.class).thenThrow(Exception.class).thenThrow(Exception.class); + + String actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "failed"); + assertTrue(actual.contains("error")); + + actual = subject.getExecutionsPerTenant(mockedRequest, "default_tenant", "successful"); + assertTrue(actual.contains("error")); + + actual = subject.getExecutionsPerTenant(mockedRequest, null, "failed"); + assertTrue(actual.contains("error")); + } + + @Test + public final void testQueryExecution() throws Exception { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + cldExecutionList.add(cldExecution); + + when(restClient.getExecutionIdSummary( + Mockito.any(), Mockito.any())).thenReturn(cldExecution); + + String actual = subject.queryExecution("id", "tenant", mockedRequest); + assertTrue(actual.contains("items")); + } + + @SuppressWarnings("unchecked") + @Test + public final void testGetActiveExecutions() throws Exception { + String tenantsList = + "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " + + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " + + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList tenantData = null; + try { + tenantData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(restClient.getTenants()).thenReturn(tenantData).thenThrow(Exception.class); + + CloudifyExecution cldExecution = + new CloudifyExecution("started", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + when(restClient.getExecutionsSummaryPerTenant(Mockito.any())) + .thenReturn(cloudifyExecutionList).thenReturn(cloudifyExecutionList); + + String actual = subject.getActiveExecutions(mockedRequest); + assertTrue(actual.contains("execution_id1")); + actual = subject.getActiveExecutions(mockedRequest); + assertTrue(actual.contains("error")); + + } + + @Test + public final void testGetNodeInstanceDetails() throws Exception { + + Map<String, Object> runtime_properties = + new HashMap<>(); + runtime_properties.put("key1", "value1"); + + CloudifyNodeInstance cfyNodeInst = + new CloudifyNodeInstance("node_instance_id1", runtime_properties); + + List<CloudifyNodeInstance> cfyNodeInstItems = new ArrayList<CloudifyNodeInstance>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstItems, null); + + when(restClient.getNodeInstanceDetails(Mockito.any(), Mockito.any())). + thenReturn(cfyNodeInstList).thenThrow(httpException). + thenThrow(Exception.class); + + String actual = + subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("node_instance_id1")); + + actual = + subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + + actual = + subject.getNodeInstanceDetails("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetNodeInstances() throws Exception { + CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); + + cfyNodeInstItems.add(cfyNodeInst); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); + + when(restClient.getNodeInstances(Mockito.any(), Mockito.any())). + thenReturn(cfyNodeInstList).thenThrow(httpException). + thenThrow(Exception.class); + + String actual = + subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("node_instance_id1")); + + actual = + subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + + actual = + subject.getNodeInstances("deploymentId", "tenant", mockedRequest); + assertTrue(actual.contains("error")); + } + + @Test + public final void testGetPlugins() throws Exception { + CloudifyPlugin sampleData = + new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); + + List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); + cfyPlugins.add(sampleData); + + CloudifyPluginList.Metadata.Pagination pageObj = + new CloudifyPluginList.Metadata.Pagination(1, 0, 1); + CloudifyPluginList.Metadata metadata = new CloudifyPluginList.Metadata(pageObj); + + CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); + + when(restClient.getPlugins()).thenReturn(cfyPluginList).thenThrow(Exception.class); + String actual = subject.getPlugins(mockedRequest); + assertTrue(actual.contains("plugin1")); + + actual = subject.getPlugins(mockedRequest); + assertTrue(actual.contains("error")); + } + + @Test + @Ignore + public final void testGetSecrets() { + + } + + @Test + @Ignore + public final void testGetSecret() { + + } + + @Test + @Ignore + public final void testDeleteSecret() { + + } + + @Test + @Ignore + public final void testCreateSecret() { + } + @SuppressWarnings({"unchecked", "unchecked"}) @Test public final void testGetBlueprintById() throws Exception { @@ -196,93 +619,13 @@ public class CloudifyControllerTest extends MockitoTestSuite { actualResult = subject.getDeploymentById("id1", null, mockedRequest); assertTrue(actualResult.contains("error")); } - - @SuppressWarnings("unchecked") - @Test - public void testGetTenantStatusForService() throws Exception { - - String[] deplIds = {"id1", "id2"}; - - CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); - - List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); - - cldDeplTenantList.add(cldDeplTenant); - - CloudifyDeployedTenantList cldDeployedTenantList = - new CloudifyDeployedTenantList(cldDeplTenantList, null); - - CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); - - List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); - cldfyTenantList.add(cldTenant); - - CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); - - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); - - List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); - - cldExecutionList.add(cldExecution); - - CloudifyExecutionList cloudifyExecutionList = - new CloudifyExecutionList(cldExecutionList, null); - - Map<String, Object> plan = new HashMap<String, Object>(); - HashMap<String, String> plugins_to_install = new HashMap<String, String>(); - plugins_to_install.put("name", "helm-plugin"); - ArrayList<HashMap<String, String>> deployment_plugins_to_install = - new ArrayList<HashMap<String, String>>(); - - deployment_plugins_to_install.add(plugins_to_install); - plan.put("deployment_plugins_to_install", deployment_plugins_to_install); - - Map<String, String> workflows = new HashMap<String, String>(); - workflows.put("status", "workflowshelm"); - plan.put("workflows", workflows); - - CloudifyBlueprint cldBp = - new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", plan); - - List<CloudifyBlueprint> items = new ArrayList<CloudifyBlueprint>(); - items.add(cldBp); - - CloudifyBlueprintList.Metadata.Pagination pageObj = - new CloudifyBlueprintList.Metadata.Pagination(1, 0, 1); - - CloudifyBlueprintList.Metadata metadata = new CloudifyBlueprintList.Metadata(pageObj); - - CloudifyBlueprintList cldBpList = new CloudifyBlueprintList(items, metadata); - - when(restClient.getTenants()).thenReturn(cloudifyTenantList); - - when(restClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList); - - when(restClient.getExecutionsSummary(Mockito.any(), Mockito.any())) - .thenReturn(cloudifyExecutionList); - - when(restClient.getBlueprint(Mockito.any(), Mockito.any())).thenReturn(cldBpList) - .thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("successful")); - - actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("error")); - - actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("error")); - } - - @SuppressWarnings("unchecked") + @Test public void testGetExecutionsByPage() throws Exception { CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); - + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); cldExecutionList.add(cldExecution); @@ -301,8 +644,8 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); - - when(restClient.getDeployments()).thenReturn(cldDeployList); + + when(restClient.getDeployments(Mockito.any(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(cldDeployList); when(restClient.getExecutions(Mockito.any(), Mockito.any())) .thenReturn(cloudifyExecutionList).thenThrow(Exception.class) .thenReturn(cloudifyExecutionList); @@ -317,13 +660,13 @@ public class CloudifyControllerTest extends MockitoTestSuite { actualResult = subject.getExecutionsByPage(mockedRequest, null, "successful", "tenant1"); assertTrue(actualResult.contains("successful")); } - +/* @SuppressWarnings("unchecked") @Test public void testGetExecutionByIdAndDeploymentId() throws Exception { CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -347,7 +690,7 @@ public class CloudifyControllerTest extends MockitoTestSuite { "tenant", mockedRequest); assertTrue(actualResult.contains("error")); } - +*/ @SuppressWarnings("unchecked") @Test public void testGetExecutionEventsById() throws Exception { @@ -384,8 +727,9 @@ public class CloudifyControllerTest extends MockitoTestSuite { @SuppressWarnings("unchecked") @Test public void testStartExecution() throws Exception { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -401,12 +745,22 @@ public class CloudifyControllerTest extends MockitoTestSuite { CloudifyNodeInstanceIdList cfyNodeInstList = new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); - + + String secretTokenStr = + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + CloudifySecret secretData = null; + try { + secretData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); + } catch (Exception e) { + + } + when(restClient.getSecret(Mockito.any(), Mockito.any())).thenReturn(secretData); + when(restClient.getNodeInstanceId(Mockito.any(), Mockito.any())) .thenReturn(cfyNodeInstList); when(restClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) - .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); + .thenReturn(cldExecution).thenThrow(Exception.class).thenThrow(httpException); String actualResult = subject.startExecution(mockedRequest, cfyExecReq); assertTrue(actualResult.contains("execution_id1")); @@ -420,32 +774,6 @@ public class CloudifyControllerTest extends MockitoTestSuite { @SuppressWarnings("unchecked") @Test - public void testUpdateDeployment() throws Exception { - - CloudifyDeploymentUpdateRequest cfyDeployUpdateReq = - new CloudifyDeploymentUpdateRequest("deployment_id", "update", false, false, - "node_instance_id1", "4", "1000", "image", 2, "my_container"); - - CloudifyDeploymentUpdateResponse cfyDeployUpdateResp = new CloudifyDeploymentUpdateResponse( - "terminated", "created_at", "update", false, "blueprint_id", "deployment_id", "", "id1", - null, "tenant1", "junit", false, "resource_availability"); - - when(restClient.updateDeployment(Matchers.<CloudifyDeploymentUpdateRequest>any())) - .thenReturn(cfyDeployUpdateResp).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); - assertTrue(actualResult.contains("terminated")); - - actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); - assertTrue(actualResult.contains("error")); - - actualResult = subject.updateDeployment(mockedRequest, cfyDeployUpdateReq); - assertTrue(actualResult.contains("error")); - - } - - @SuppressWarnings("unchecked") - @Test public void testGetNodeInstanceId() throws Exception { CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); @@ -506,8 +834,9 @@ public class CloudifyControllerTest extends MockitoTestSuite { HttpHeaders httpHeader = new HttpHeaders(); httpHeader.put("tenant", tenants); - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "cancel", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + CloudifyExecution cfyExecObj = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); when(restClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java deleted file mode 100644 index 7097275..0000000 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/CommonApiControllerTest.java +++ /dev/null @@ -1,791 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ - -package org.onap.ccsdk.dashboard.controller; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Stream; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.dashboard.core.MockUser; -import org.onap.ccsdk.dashboard.core.MockitoTestSuite; -import org.onap.ccsdk.dashboard.domain.EcdComponent; -import org.onap.ccsdk.dashboard.exceptions.BadRequestException; -import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; -import org.onap.ccsdk.dashboard.exceptions.DownstreamException; -import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; -import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; -import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; -import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployment; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifyTenant; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentInput; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; -import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; -import org.onap.ccsdk.dashboard.model.inventory.Service; -import org.onap.ccsdk.dashboard.model.inventory.ServiceList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; -import org.onap.ccsdk.dashboard.model.inventory.ServiceRef; -import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceType; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; -import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeUploadRequest; -import org.onap.ccsdk.dashboard.rest.CloudifyClient; -import org.onap.ccsdk.dashboard.rest.DeploymentHandlerClient; -import org.onap.ccsdk.dashboard.rest.InventoryClient; -import org.onap.ccsdk.dashboard.service.ControllerEndpointService; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.web.client.HttpServerErrorException; -import org.springframework.web.client.HttpStatusCodeException; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; - -public class CommonApiControllerTest extends MockitoTestSuite { - - @Mock - private CloudifyClient cfyClient; - - @Mock - private InventoryClient inventoryClient; - - @Mock - DeploymentHandlerClient deploymentHandlerClient; - - @Mock - ControllerEndpointService controllerEndpointService; - - @InjectMocks - CommonApiController subject = new CommonApiController(); - - private HttpStatusCodeException httpException = - new HttpServerErrorException(HttpStatus.BAD_GATEWAY); - - protected final ObjectMapper objectMapper = new ObjectMapper(); - - HttpServletRequest mockedRequest; - HttpServletResponse mockedResponse; - - MockUser mockUser = new MockUser(); - ServiceList deplList = null; - Service deplItem = null; - - ServiceType bpItem = null; - ServiceType bpItem2 = null; - ServiceTypeList bpList = null; - ServiceTypeList bpList2 = null; - - ServiceTypeRequest bpUploadItem = null; - - BadRequestException badReqError; - ServiceAlreadyExistsException srvcExistError; - ServerErrorException serverError; - DownstreamException downStrmError; - JsonProcessingException jsonError; - DeploymentNotFoundException notFoundError; - private ServiceTypeNotFoundException serviceTypeException = - new ServiceTypeNotFoundException("Invalid blueprint"); - - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - objectMapper.registerModule(new Jdk8Module()); - getExpectedDeployments(); - getExpectedBueprints(); - createBpUploadItem(); - mockedRequest = getMockedRequest(); - mockedResponse = getMockedResponse(); - badReqError = new BadRequestException("bad request"); - srvcExistError = new ServiceAlreadyExistsException("service already exists"); - serverError = new ServerErrorException("Error occured in server"); - downStrmError = new DownstreamException("error occured in downstream"); - notFoundError = new DeploymentNotFoundException("item not found"); - } - - public void getExpectedDeployments() - throws JsonParseException, JsonMappingException, IOException { - - deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, - "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); - Collection<Service> items = new ArrayList<Service>(); - items.add(deplItem); - - String pageLinks = - "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; - ServiceList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); - int totalCount = 1; - deplList = new ServiceList(items, totalCount, paginationLinks); - - } - - public void getExpectedBueprints() - throws JsonParseException, JsonMappingException, IOException { - bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, - "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); - - Collection<ServiceType> items = new ArrayList<ServiceType>(); - items.add(bpItem); - - String pageLinks2 = - "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; - ServiceTypeList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); - int totalCount = 1; - bpList = new ServiceTypeList(items, totalCount, paginationLinks); - - bpItem2 = new ServiceType("xyz1731", "xyz1731-helm-1907", 1906, - "tosca_definitions_version: cloudify_dsl_1_3\\r\\nimports:\\r\\n - http://www.getcloudify.org/spec/cloudify/4.2/types.yaml\\r\\n", - "app1", "comp1", null, null, null, null, null, null, "typeId", null, "created", null, - true); - - Collection<ServiceType> items2 = new ArrayList<ServiceType>(); - items2.add(bpItem2); - - bpList2 = new ServiceTypeList(items2, totalCount, paginationLinks); - } - - public void createBpUploadItem() { - bpUploadItem = ServiceTypeRequest.from(bpItem); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public final void testInsertComponent() throws Exception { - EcdComponent component1 = new EcdComponent(); - - component1.setCname("comp1"); - component1.setCompId(100L); - component1.setDname("COMP1"); - - doNothing().when(controllerEndpointService).insertComponent(component1); - - String actualResult = subject.insertComponent(mockedRequest, component1); - assertTrue(actualResult.contains("Inserted")); - } - - @Test - public final void testGetComponents() throws Exception { - EcdComponent component1 = new EcdComponent(); - EcdComponent component2 = new EcdComponent(); - - component1.setCname("comp1"); - component1.setCompId(100L); - component1.setDname("COMP1"); - - component2.setCname("comp2"); - component2.setCompId(200L); - component2.setDname("COMP2"); - - List<EcdComponent> compsList = new ArrayList<EcdComponent>(); - compsList.add(component1); - compsList.add(component2); - - when(controllerEndpointService.getComponents()).thenReturn(compsList); - - String actualResult = subject.getComponents(mockedRequest); - assertTrue(actualResult.contains("comp1")); - } - - @Test - public final void testGetTenants() throws Exception { - String tenantsList = - "{\"items\": [{\"id\": 1, \"name\": \"default_tenant\", \"dName\": \"default_tenant\" }, " - + "{\"id\": 2, \"name\": \"dyh1b1902\", \"dName\": \"dyh1b1902\"}], " - + "\"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; - CloudifyTenantList sampleData = null; - try { - sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); - } catch (Exception e) { - } - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - - Mockito.when(cfyClient.getTenants()).thenReturn(sampleData); - - String tenantStr = subject.getTenants(mockedRequest); - assertTrue(tenantStr.contains("dyh1b")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testGetTenantStatusForService() throws Exception { - String[] deplIds = {"id1", "id2"}; - - CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); - - List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); - - cldDeplTenantList.add(cldDeplTenant); - - CloudifyDeployedTenantList cldDeployedTenantList = - new CloudifyDeployedTenantList(cldDeplTenantList, null); - - CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); - - List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); - cldfyTenantList.add(cldTenant); - - CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); - - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); - - List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); - - cldExecutionList.add(cldExecution); - - CloudifyExecutionList cloudifyExecutionList = - new CloudifyExecutionList(cldExecutionList, null); - - when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); - - when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList); - - when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) - .thenReturn(cloudifyExecutionList).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("successful")); - - actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("error")); - - actualResult = subject.getTenantStatusForService(mockedRequest, deplIds); - assertTrue(actualResult.contains("error")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testCreateBlueprint() throws Exception { - ServiceTypeUploadRequest bpUploadReq = ServiceTypeUploadRequest.from(bpItem); - - when(inventoryClient.addServiceType(Matchers.<ServiceTypeRequest>any())) - .thenThrow(BlueprintParseException.class).thenThrow(httpException) - .thenThrow(Exception.class).thenReturn(bpItem); - - String actual1 = subject.createBlueprint(mockedRequest, bpUploadReq); - assertTrue(actual1.contains("error")); - - String actual2 = subject.createBlueprint(mockedRequest, bpUploadReq); - assertTrue(actual2.contains("error")); - - String actual3 = subject.createBlueprint(mockedRequest, bpUploadReq); - assertTrue(actual3.contains("error")); - - String actual = subject.createBlueprint(mockedRequest, bpUploadReq); - assertTrue(actual.contains("app1")); - - } - - @SuppressWarnings("unchecked") - @Test - public final void testGetBlueprintsByPage() { - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("_include", "typeName,typeId,typeVersion"); - mockedRequest1.addParameter("name", "xyz"); - - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream1).thenThrow(Exception.class).thenThrow(httpException); - - String result = subject.getBlueprintsByPage(mockedRequest1); - assertTrue(result.contains("xyz")); - - result = subject.getBlueprintsByPage(mockedRequest1); - assertTrue(result.contains("error")); - - result = subject.getBlueprintsByPage(mockedRequest1); - assertTrue(result.contains("error")); - - } - - @SuppressWarnings("unchecked") - @Test - public final void testQueryBlueprintFilter() { - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("_include", "typeName,typeId,typeVersion"); - mockedRequest1.addParameter("name", "xyz"); - - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream1).thenThrow(Exception.class).thenThrow(httpException); - - String result = subject.queryBlueprintFilter(mockedRequest1); - assertTrue(result.contains("xyz")); - - result = subject.queryBlueprintFilter(mockedRequest1); - assertTrue(result.contains("error")); - - result = subject.queryBlueprintFilter(mockedRequest1); - assertTrue(result.contains("error")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testGetDeploymentsByPage() { - CloudifyDeployedTenant cldDeplTenant = - new CloudifyDeployedTenant("dcae_dtiapi_1902", "dcae_dtiapi_1902", "tenant1"); - - List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); - - cldDeplTenantList.add(cldDeplTenant); - - CloudifyDeployedTenantList cldDeployedTenantList = - new CloudifyDeployedTenantList(cldDeplTenantList, null); - - CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); - - List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); - cldfyTenantList.add(cldTenant); - - CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); - - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("_include", "id"); - mockedRequest1.addParameter("searchBy", "dti"); - - Collection<Service> items = deplList.items; - - when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); - - when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList) - .thenThrow(Exception.class).thenThrow(httpException).thenReturn(cldDeployedTenantList) - .thenReturn(cldDeployedTenantList); - - Stream<Service> sampleStream1 = items.stream(); - Stream<Service> sampleStream2 = items.stream(); - Stream<Service> sampleStream3 = items.stream(); - - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1) - .thenReturn(sampleStream2).thenReturn(sampleStream3).thenThrow(Exception.class) - .thenThrow(httpException); - - String result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); - assertTrue(result.contains("error")); - - result = subject.getDeploymentsByPage("dcae_dtiapi_1902", mockedRequest1); - assertTrue(result.contains("error")); - - } - - @SuppressWarnings("unchecked") - @Test - public final void testGetAllDeploymentsByPage() { - CloudifyDeployedTenant cldDeplTenant = - new CloudifyDeployedTenant("dcae_dtiapi_1902", "dcae_dtiapi_1902", "tenant1"); - - List<CloudifyDeployedTenant> cldDeplTenantList = new ArrayList<CloudifyDeployedTenant>(); - - cldDeplTenantList.add(cldDeplTenant); - - CloudifyDeployedTenantList cldDeployedTenantList = - new CloudifyDeployedTenantList(cldDeplTenantList, null); - - CloudifyTenant cldTenant = new CloudifyTenant("tenant1", "tenant1", "tenant_id1"); - - List<CloudifyTenant> cldfyTenantList = new ArrayList<CloudifyTenant>(); - cldfyTenantList.add(cldTenant); - - CloudifyTenantList cloudifyTenantList = new CloudifyTenantList(cldfyTenantList, null); - - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("_include", "id"); - mockedRequest1.addParameter("searchBy", "dti"); - - Collection<Service> items = deplList.items; - - when(cfyClient.getTenants()).thenReturn(cloudifyTenantList); - - when(cfyClient.getTenantInfoFromDeploy(Mockito.any())).thenReturn(cldDeployedTenantList) - .thenThrow(Exception.class).thenThrow(httpException).thenReturn(cldDeployedTenantList) - .thenReturn(cldDeployedTenantList); - - Stream<Service> sampleStream1 = items.stream(); - Stream<Service> sampleStream2 = items.stream(); - Stream<Service> sampleStream3 = items.stream(); - - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1) - .thenReturn(sampleStream2).thenReturn(sampleStream3).thenThrow(Exception.class) - .thenThrow(httpException); - - String result = subject.getAllDeploymentsByPage(mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getAllDeploymentsByPage(mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getAllDeploymentsByPage(mockedRequest1); - assertTrue(result.contains("dti")); - - result = subject.getAllDeploymentsByPage(mockedRequest1); - assertTrue(result.contains("error")); - - result = subject.getAllDeploymentsByPage(mockedRequest1); - assertTrue(result.contains("error")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testGetDeploymentRevisions() throws Exception { - CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); - - List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); - cfyNodeInstanceItems.add(cfyNodeInstance); - - CloudifyNodeInstanceList cfyNodeInstList = - new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); - - when(cfyClient.getNodeInstanceVersion(Mockito.any(), Mockito.any())) - .thenReturn(cfyNodeInstList).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = - subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); - assertTrue(actualResult.contains("id1")); - - actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); - assertTrue(actualResult.contains("error")); - - actualResult = subject.getDeploymentRevisions("deploymentId", "tenant", mockedRequest); - assertTrue(actualResult.contains("error")); - } - - @Test - public final void testGetDeploymentInputs() throws Exception { - - Map<String, Object> inputHash = new HashMap<String, Object>(); - inputHash.put("key1", "value1"); - - CloudifyDeployment cldDeployment = - new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", - inputHash, null, null, null, null, null, null, "tenant"); - - List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); - cfyDeployItems.add(cldDeployment); - - CloudifyDeploymentList.Metadata.Pagination pageObj = - new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); - CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); - - CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); - - when(cfyClient.getDeploymentInputs(Matchers.any(), Matchers.any())) - .thenReturn(cldDeployList); - - String actualResult = subject.getDeploymentInputs("deploymentId", "tenant", mockedRequest); - assertTrue(actualResult.contains("blueprint_id")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testModifyDeployment() throws Exception { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); - - Map<String, Object> params = new HashMap<String, Object>(); - params.put("tenant", "tenant1"); - params.put("workflow", "upgrade"); - - CloudifyExecutionRequest cfyExecReq = new CloudifyExecutionRequest("deployment_id", - "upgrade", false, false, "tenant1", params); - - CloudifyNodeInstanceId cfyNodeInst = new CloudifyNodeInstanceId("node_instance_id1"); - - List<CloudifyNodeInstanceId> cfyNodeInstItems = new ArrayList<CloudifyNodeInstanceId>(); - - cfyNodeInstItems.add(cfyNodeInst); - - CloudifyNodeInstanceIdList cfyNodeInstList = - new CloudifyNodeInstanceIdList(cfyNodeInstItems, null); - - when(cfyClient.getNodeInstanceId(Mockito.any(), Mockito.any())).thenReturn(cfyNodeInstList); - - when(cfyClient.startExecution(Matchers.<CloudifyExecutionRequest>any())) - .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); - - String inputParamStr = "{\"tenant\": \"tenant1\", \"workflow\":\"upgrade\"}"; - - InputStream is = new ByteArrayInputStream(inputParamStr.getBytes()); - - String actualResult = subject.modifyDeployment("depId", mockedRequest, is); - assertTrue(actualResult.contains("execution_id1")); - - actualResult = subject.modifyDeployment("depId", mockedRequest, is); - assertTrue(actualResult.contains("error")); - - actualResult = subject.modifyDeployment("depId", mockedRequest, is); - assertTrue(actualResult.contains("error")); - - } - - @Test - public final void testGetServicesForType() throws Exception { - ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); - Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); - expectedSrvcIds.add(expectedSrvc); - ServiceRefList expectedSrvcRefList = new ServiceRefList(expectedSrvcIds, 1); - - when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) - .thenReturn(expectedSrvcRefList); - String actual = subject.getServicesForType(mockedRequest, "typeId1"); - assertTrue(actual.contains("typeId1")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testCreateDeployment() throws Exception { - DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", - "xyz1731-helm-1906", 1906, "blueprintId", null, "tenant1"); - - DeploymentInput deployInput2 = new DeploymentInput("component1", "tag1", - "xyz1731-helm-1906", 1906, null, null, "tenant1"); - - DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); - DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); - - Collection<ServiceType> items = bpList2.items; - Stream<ServiceType> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream1); - - String actualResp0 = subject.createDeployment(mockedRequest, deployInput2); - assertTrue(actualResp0.contains("error")); - - StringBuffer expectedStrBuff = new StringBuffer(); - expectedStrBuff.append("http://oom.s2.com"); - when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); - - when(deploymentHandlerClient.putDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) - .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) - .thenThrow(Exception.class); - - String actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("component1")); - - actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.createDeployment(mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - } - - @SuppressWarnings("unchecked") - @Test - public final void testUpdateDeployment() throws Exception { - - DeploymentInput deployInput1 = new DeploymentInput("component1", "tag1", - "xyz1731-helm-1906", 1906, "blueprintId", null, "tenant1"); - - DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); - DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); - - Collection<ServiceType> items = bpList2.items; - Stream<ServiceType> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream1); - - when(deploymentHandlerClient.updateDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) - .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) - .thenThrow(Exception.class); - - String actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("req1")); - - actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - - actualResp = subject.updateDeployment("id1", mockedRequest, deployInput1); - assertTrue(actualResp.contains("error")); - } - - @Test - public final void testGetExecutionByDeploymentId() throws Exception { - - CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); - - List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); - - cldExecutionList.add(cldExecution); - - CloudifyExecutionList cloudifyExecutionList = - new CloudifyExecutionList(cldExecutionList, null); - - when(cfyClient.getExecutionsSummary(Mockito.any(), Mockito.any())) - .thenReturn(cloudifyExecutionList); - - String actualResult = - subject.getExecutionByDeploymentId("dep_id", "tenant1", mockedRequest); - assertTrue(actualResult.contains("execution_id1")); - } - - @Test - public final void testDeleteBlueprint() throws Exception { - String expected = "{\"202\": \"OK\"}"; - doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) - .deleteServiceType(Matchers.anyString()); - - String actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); - assertEquals(expected, actual); - - actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteBlueprint("srvcId", mockedRequest, mockedResponse); - assertTrue(actual.contains("error")); - } - - @Test - public final void testDeleteDeployment() throws Exception { - doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) - .doThrow(notFoundError).doThrow(Exception.class).when(deploymentHandlerClient) - .deleteDeployment(Matchers.anyString(), Matchers.anyString()); - - StringBuffer expectedStrBuff = new StringBuffer(); - expectedStrBuff.append("http://oom.s2.com"); - when(mockedRequest.getRequestURL()).thenReturn(expectedStrBuff); - - String actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertFalse(actual.contains("error")); - - actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteDeployment("dep1", mockedRequest, "tenant1", mockedResponse); - assertTrue(actual.contains("error")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testCancelExecution() throws Exception { - List<String> tenants = new ArrayList<String>(); - tenants.add("tenant1"); - - HttpHeaders httpHeader = new HttpHeaders(); - httpHeader.put("tenant", tenants); - - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "cancel", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); - - when(cfyClient.cancelExecution(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(cfyExecObj).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = - subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); - assertTrue(actualResult.contains("execution_id1")); - - actualResult = - subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); - assertTrue(actualResult.contains("error")); - - actualResult = - subject.cancelExecution(httpHeader, "id1", null, mockedRequest, mockedResponse); - assertTrue(actualResult.contains("error")); - } - -} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java index 3d71a2e..53657ed 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/ConsulControllerTest.java @@ -28,6 +28,8 @@ import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; +import javax.servlet.http.HttpServletRequest; + import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -37,14 +39,15 @@ import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.ccsdk.dashboard.controller.ConsulController.ConsulDataItem; import org.onap.ccsdk.dashboard.core.MockUser; import org.onap.ccsdk.dashboard.core.MockitoTestSuite; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulHealthServiceRegistration; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; import org.onap.ccsdk.dashboard.model.RestResponseSuccess; +import org.onap.ccsdk.dashboard.model.consul.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.consul.ConsulHealthServiceRegistration; +import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; import org.onap.ccsdk.dashboard.rest.ConsulClient; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.web.support.UserUtils; @@ -67,6 +70,8 @@ public class ConsulControllerTest extends MockitoTestSuite { MockUser mockUser = new MockUser(); HttpClientErrorException httpException; + String[] svcTags = {"cfytenantname=onap"}; + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); @@ -87,7 +92,7 @@ public class ConsulControllerTest extends MockitoTestSuite { "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", - "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); @@ -118,7 +123,7 @@ public class ConsulControllerTest extends MockitoTestSuite { "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", - "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); @@ -160,7 +165,7 @@ public class ConsulControllerTest extends MockitoTestSuite { "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", - "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); @@ -193,123 +198,15 @@ public class ConsulControllerTest extends MockitoTestSuite { assertTrue(actualResult.contains("dc1")); } - @SuppressWarnings("unchecked") - @Test - public final void testRegisterService() throws Exception { - ConsulHealthServiceRegistration.EndpointCheck endPoint = - new ConsulHealthServiceRegistration.EndpointCheck("endpoint1", "interval1", - "description1", "name1"); - List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = - new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); - endPointList.add(endPoint); - - List<String> tagList = new ArrayList<String>(); - tagList.add("tag1"); - tagList.add("tag2"); - - ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = - new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "name1", - "address1", "port1", tagList, endPointList); - List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = - new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); - servcRegList.add(servcReg); - - ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); - - RestResponseSuccess expectedResp = new RestResponseSuccess("Registration yielded code 0"); - String expectedResult = objectMapper.writeValueAsString(expectedResp); - - String expectedStr = "Registration yielded code 0"; - when(consulClient.registerService(Matchers.<ConsulHealthServiceRegistration>any())) - .thenReturn(expectedStr).thenThrow(Exception.class).thenThrow(httpException); - - String actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.equals(expectedResult)); - - actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.contains("error")); - - actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.contains("error")); - } - - @Test - public final void testRegisterService_SrvcError() throws Exception { - ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(null); - - String actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.contains("error")); - } - - @Test - @Ignore - public final void testRegisterService_invalidSrvcError() throws Exception { - ConsulHealthServiceRegistration.EndpointCheck endPoint = - new ConsulHealthServiceRegistration.EndpointCheck("endpoint1", "interval1", - "description1", "name1"); - List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = - new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); - endPointList.add(endPoint); - - List<String> tagList = new ArrayList<String>(); - tagList.add("tag1"); - tagList.add("tag2"); - - ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = - new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "name2", - "address2", "port1", tagList, endPointList); - List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = - new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); - servcRegList.add(servcReg); - - ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); - - String actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.contains("error")); - } - - @Test - public final void testRegisterService_invalidEndptError() throws Exception { - ConsulHealthServiceRegistration.EndpointCheck endPoint = - new ConsulHealthServiceRegistration.EndpointCheck("", "", "description1", "name1"); - List<ConsulHealthServiceRegistration.EndpointCheck> endPointList = - new ArrayList<ConsulHealthServiceRegistration.EndpointCheck>(); - endPointList.add(endPoint); - - List<String> tagList = new ArrayList<String>(); - tagList.add("tag1"); - tagList.add("tag2"); - - ConsulHealthServiceRegistration.ConsulServiceRegistration servcReg = - new ConsulHealthServiceRegistration.ConsulServiceRegistration("id1", "", "", "port1", - tagList, endPointList); - List<ConsulHealthServiceRegistration.ConsulServiceRegistration> servcRegList = - new ArrayList<ConsulHealthServiceRegistration.ConsulServiceRegistration>(); - servcRegList.add(servcReg); - - ConsulHealthServiceRegistration chsrObj = new ConsulHealthServiceRegistration(servcRegList); - - String actualResult = subject.registerService(mockedRequest, chsrObj); - assertTrue(actualResult.contains("error")); - } - - @SuppressWarnings("unchecked") @Test - public final void testDeregisterService() throws Exception { - RestResponseSuccess expectedResp = new RestResponseSuccess("Deregistration yielded code 0"); - String expectedResult = objectMapper.writeValueAsString(expectedResp); - - when(consulClient.deregisterService(Mockito.any())).thenReturn(0).thenThrow(Exception.class) - .thenThrow(httpException); - - String actualResult = subject.deregisterService(mockedRequest, "srvc1"); - assertTrue(actualResult.equals(expectedResult)); - - actualResult = subject.deregisterService(mockedRequest, "srvc1"); - assertTrue(actualResult.contains("error")); - - actualResult = subject.deregisterService(mockedRequest, "srvc1"); + public final void testGetItemListForPageWrapper() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + user.setId(1000L); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + String actualResult = + subject.getItemListForPageWrapper(mockedRequest, "dc1", ConsulController.ConsulDataItem.SERVICE_INFO); assertTrue(actualResult.contains("error")); + } - } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java index 6517b68..4833c12 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/DeploymentHandlerControllerTest.java @@ -27,6 +27,8 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; +import javax.servlet.http.HttpServletRequest; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -88,46 +90,13 @@ public class DeploymentHandlerControllerTest extends MockitoTestSuite { @Test public final void testPutDeployment_create() throws Exception { DeploymentRequestObject expectReq = - new DeploymentRequestObject("dep1", "dep1", null, "tenant1", "create"); - + new DeploymentRequestObject("dep1", "dep1", "create", null, "tenant1"); + DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); - + when(restClient.putDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) - .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) - .thenThrow(Exception.class); - - String actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("req1")); - - actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("error")); - - actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("error")); - - actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("error")); - - actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("error")); - - actualResp = subject.putDeployment(mockedRequest, expectReq); - assertTrue(actualResp.contains("error")); - } - - @SuppressWarnings("unchecked") - @Test - public final void testPutDeployment_update() throws Exception { - DeploymentRequestObject expectReq = - new DeploymentRequestObject("dep1", "dep1", null, "tenant1", "update"); - - DeploymentResponseLinks expectLink = new DeploymentResponseLinks("self", "status"); - DeploymentResponse expectResp = new DeploymentResponse("req1", expectLink); - - when(restClient.updateDeployment(Matchers.anyString(), Matchers.anyString(), - Matchers.<DeploymentRequest>any())).thenReturn(expectResp).thenThrow(badReqError) + Matchers.<DeploymentRequest>any(), Matchers.<HttpServletRequest>any()) ).thenReturn(expectResp).thenThrow(badReqError) .thenThrow(srvcExistError).thenThrow(serverError).thenThrow(downStrmError) .thenThrow(Exception.class); @@ -155,7 +124,7 @@ public class DeploymentHandlerControllerTest extends MockitoTestSuite { doNothing().doThrow(badReqError).doThrow(serverError).doThrow(downStrmError) .doThrow(notFoundError).doThrow(Exception.class).when(restClient) - .deleteDeployment(Matchers.anyString(), Matchers.anyString()); + .deleteDeployment(Matchers.anyString(), Matchers.anyString(), Matchers.<HttpServletRequest>any()); StringBuffer expectedStrBuff = new StringBuffer(); expectedStrBuff.append("http://oom.s2.com"); diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java index 01858ed..9cce55e 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/controller/InventoryControllerTest.java @@ -31,6 +31,8 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; @@ -54,6 +56,7 @@ import org.onap.ccsdk.dashboard.core.MockitoTestSuite; import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceNotFoundException; import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; import org.onap.ccsdk.dashboard.model.inventory.Service; import org.onap.ccsdk.dashboard.model.inventory.ServiceList; import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams; @@ -63,10 +66,14 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceType; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; import org.onap.ccsdk.dashboard.rest.CloudifyClient; import org.onap.ccsdk.dashboard.rest.InventoryClient; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.util.CacheManager; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.portalsdk.core.web.support.AppUtils; import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; @@ -82,11 +89,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) -@PrepareForTest({DashboardProperties.class}) public class InventoryControllerTest extends MockitoTestSuite { @Mock - private CloudifyClient restClient; + private CloudifyClient cfyClient; @Mock private InventoryClient inventoryClient; @@ -118,59 +124,63 @@ public class InventoryControllerTest extends MockitoTestSuite { HttpServletResponse mockedResponse; MockUser mockUser = new MockUser(); - ServiceList deplList = null; - Service deplItem = null; - ServiceType bpItem = null; - ServiceTypeList bpList = null; + ServiceTypeSummary bpItem, bpItem2 = null; + ServiceTypeSummaryList bpList, bpList2 = null; + ServiceType bpItemFull = null; + ServiceTypeList bpItemFullList = null; + ServiceTypeRequest bpUploadItem = null; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); objectMapper.registerModule(new Jdk8Module()); - getExpectedDeployments(); - getExpectedBueprints(); + getExpectedBlueprints(); createBpUploadItem(); mockedRequest = getMockedRequest(); mockedResponse = getMockedResponse(); + CacheManager testCache = new CacheManager(); + Map<String, List<ServiceTypeSummary>> bpPerOwner = new HashMap<String, List<ServiceTypeSummary>>(); + bpPerOwner.put("xyz1731", (List<ServiceTypeSummary>)bpList2.items); + testCache.putObject("owner_bp_map", bpPerOwner); + subject.setCacheManager(testCache); + /* + PowerMockito.mockStatic(SystemProperties.class); + Mockito + .when(SystemProperties.getProperty("cache_switch")) + .thenReturn("1"); + */ } - public void getExpectedDeployments() - throws JsonParseException, JsonMappingException, IOException { - - deplItem = new Service("dcae_dtiapi_1902", null, "1552335532348", "1552335532348", null, - "dummyVnfId", null, "dummyVnfType", "dummyLocation", "dcae_dtiapi_1902", null); - Collection<Service> items = new ArrayList<Service>(); - items.add(deplItem); - - String pageLinks = - "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; - ServiceList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks, ServiceList.PaginationLinks.class); - int totalCount = 1; - deplList = new ServiceList(items, totalCount, paginationLinks); - - } - - public void getExpectedBueprints() + public void getExpectedBlueprints() throws JsonParseException, JsonMappingException, IOException { - bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1"). + typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", "123-456-789", + "342343", true); + bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); - Collection<ServiceType> items = new ArrayList<ServiceType>(); + + Collection<ServiceTypeSummary> items = new ArrayList<ServiceTypeSummary>(); items.add(bpItem); + Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); + items2.add(bpItem2); + String pageLinks2 = "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; - ServiceTypeList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); + ServiceTypeSummaryList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks2, ServiceTypeSummaryList.PaginationLinks.class); int totalCount = 1; - bpList = new ServiceTypeList(items, totalCount, paginationLinks); + bpList = new ServiceTypeSummaryList(items, totalCount, paginationLinks); + bpList2 = new ServiceTypeSummaryList(items2, totalCount, paginationLinks); } public void createBpUploadItem() { - bpUploadItem = ServiceTypeRequest.from(bpItem); + bpUploadItem = ServiceTypeRequest.from(bpItemFull); } @After @@ -178,465 +188,229 @@ public class InventoryControllerTest extends MockitoTestSuite { } @Test + public final void testGetOwnersByPage() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @Test + public final void testGetAllServiceTypeNames() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getAllServiceTypeNames(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @Test + public final void testGetAllServiceTypeIds() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); + String result = subject.getAllServiceTypeIds(mockedRequest); + assertTrue(result.contains("xyz")); + } + + @Test public final void testGetServiceTypesByPage() { User user = mockUser.mockUser(); user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("searchBy", "xyz"); + //mockedRequest.addParameter("searchBy", "xyz"); mockedRequest.addParameter("sortBy", "owner"); + // # 1st case Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - - Collection<ServiceType> items = bpList.items; - - Stream<ServiceType> sampleStream1 = items.stream(); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - + + // # 2nd case HttpSession session = mockedRequest.getSession(); HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); comp_deploy_tab.put("comp1", true); - Set<String> userApps = new TreeSet<String>(); userApps.add("comp1"); - when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); when(session.getAttribute("role_level")).thenReturn("app"); when(session.getAttribute("authComponents")).thenReturn(userApps); - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + Stream<ServiceTypeSummary> sampleStream2 = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()) .thenReturn(sampleStream2); + /* + Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) + .thenReturn(sampleStream2); + */ String result2 = subject.getServiceTypesByPage(mockedRequest); assertTrue(result2.contains("xyz")); - } + } + @Test - public final void testGetServiceTypesByPage_appl() { + public final void testGetServiceTypesByPage_appDevUser() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("sortBy", "application"); - - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + HttpSession session = mockedRequest.getSession(); + HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); + comp_deploy_tab.put("comp1", true); + Set<String> userApps = new TreeSet<String>(); + userApps.add("comp1"); + when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); + when(session.getAttribute("role_level")).thenReturn("app_dev"); + when(session.getAttribute("authComponents")).thenReturn(userApps); - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); + } + + @Test + public final void testGetServiceTypesByPage_containsFilter() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "contains:xyz1731-helm-1906"); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream); - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("error")); } + + @Test + public final void testGetServiceTypesByPage_AllFilters() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + mockedRequest.addParameter("searchBy", "serviceRef:xyz1731-helm-1906;app:app1;comp:comp1;owner:xyz1731;"); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); + + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> sampleStream = items.stream(); + Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream); + String result = subject.getServiceTypesByPage(mockedRequest); + assertTrue(result.contains("xyz")); + + } + @Test public final void testGetServiceTypesByPage_comp() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "component"); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); } @Test public final void testGetServiceTypesByPage_typeId() { + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeId"); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); } @Test public final void testGetServiceTypesByPage_typeName() { - + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeName"); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); - } @Test public final void testGetServiceTypesByPage_typeVer() { - + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "typeVersion"); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); - } @Test public final void testGetServiceTypesByPage_created() { - + User user = mockUser.mockUser(); + user.setLoginId("tester"); MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); mockedRequest.addParameter("sortBy", "created"); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream1 = items.stream(); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); + Collection<ServiceTypeSummary> items = bpList2.items; + Stream<ServiceTypeSummary> sampleStream1 = items.stream(); Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream1); String result = subject.getServiceTypesByPage(mockedRequest); assertTrue(result.contains("xyz")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<ServiceType> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream2); - String result2 = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result2.contains("xyz")); } - @Test - public final void testGetServiceTypesByPage_Auth() { - - User user = mockUser.mockUser(); - user.setLoginId("tester"); - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("searchBy", "xyz"); - - Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream = items.stream(); - - HttpSession session = mockedRequest.getSession(); - HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); - comp_deploy_tab.put("comp1", true); - - Set<String> userApps = new TreeSet<String>(); - userApps.add("comp1"); - - when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); - when(session.getAttribute("role_level")).thenReturn("ops"); - when(session.getAttribute("authComponents")).thenReturn(userApps); - - Mockito.when(inventoryClient.getServiceTypes(Matchers.<ServiceTypeQueryParams>any())) - .thenReturn(sampleStream); - String result = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result.contains("xyz")); - } @SuppressWarnings("unchecked") @Test public final void testGetServiceTypesByPage_Exception() { - PowerMockito.mockStatic(DashboardProperties.class); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream = items.stream(); - when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); when(inventoryClient.getServiceTypes()).thenThrow(RestClientException.class) - .thenThrow(httpException).thenReturn(sampleStream); + .thenThrow(httpException); String errResp = subject.getServiceTypesByPage(mockedRequest); assertTrue(errResp.contains("error")); errResp = subject.getServiceTypesByPage(mockedRequest); assertTrue(errResp.contains("error")); - - String result = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result.contains("xyz")); - } - - @Test - public final void testGetServiceTypesByPage_Filter() { - User user = mockUser.mockUser(); - user.setLoginId("tester"); - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("searchBy", "xyz"); - PowerMockito.mockStatic(DashboardProperties.class); - Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> sampleStream = items.stream(); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - Mockito.when(inventoryClient.getServiceTypes()).thenReturn(sampleStream); - - String result = subject.getServiceTypesByPage(mockedRequest); - assertTrue(result.contains("xyz")); } - @Test - public final void testGetServicesByPage_auth() throws IOException { - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("searchBy", "dti"); - Collection<Service> items = deplList.items; - - HttpSession session = mockedRequest1.getSession(); - HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); - comp_deploy_tab.put("dcae", true); - - Set<String> userApps = new TreeSet<String>(); - userApps.add("dcae"); - - when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); - when(session.getAttribute("role_level")).thenReturn("app"); - when(session.getAttribute("authComponents")).thenReturn(userApps); - - Stream<Service> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); - - String result1 = subject.getServicesByPage(mockedRequest1); - assertTrue(result1.contains("dti")); - - } - - @Test - public final void testGetServicesByPage_auth_ops() throws IOException { - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("searchBy", "dti"); - - Collection<Service> items = deplList.items; - - HttpSession session = mockedRequest1.getSession(); - HashMap<String, Boolean> comp_deploy_tab = new HashMap<String, Boolean>(); - comp_deploy_tab.put("dcae", true); - - Set<String> userApps = new TreeSet<String>(); - userApps.add("dcae"); - - when(session.getAttribute("comp_access")).thenReturn(comp_deploy_tab); - when(session.getAttribute("role_level")).thenReturn("ops"); - when(session.getAttribute("authComponents")).thenReturn(userApps); - - Stream<Service> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); - - String result1 = subject.getServicesByPage(mockedRequest1); - assertTrue(result1.contains("dti")); - - } - - @Test - public final void testGetServicesByPage() throws IOException { - /* - * User user = mockUser.mockUser(); user.setLoginId("tester"); - */ - MockHttpServletRequestWrapper mockedRequest1 = getMockedRequest(); - mockedRequest1.addParameter("searchBy", "dti"); - mockedRequest1.addParameter("sortBy", "deploymentRef"); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - - Collection<Service> items = deplList.items; - - Stream<Service> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); - - String result1 = subject.getServicesByPage(mockedRequest1); - assertTrue(result1.contains("dti")); - } - - @Test - public final void testGetServicesByPage_sort_serviceId() throws IOException { - - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("sortBy", "serviceId"); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - - Collection<Service> items = deplList.items; - - Stream<Service> sampleStream1 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream1); - - String result = subject.getServicesByPage(mockedRequest); - assertTrue(result.contains("dti")); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<Service> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); - - String result2 = subject.getServicesByPage(mockedRequest); - assertTrue(result2.contains("dti")); - } - - @Test - public final void testGetServicesByPage_sort_created() throws IOException { - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("sortBy", "created"); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - - Collection<Service> items = deplList.items; - - Stream<Service> sampleStream = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream); - - String result = subject.getServicesByPage(mockedRequest); - assertTrue(result.contains("dti")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<Service> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); - - String result2 = subject.getServicesByPage(mockedRequest); - assertTrue(result2.contains("dti")); - - } - - @Test - public final void testGetServicesByPage_sort_modified() throws IOException { - - MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); - mockedRequest.addParameter("sortBy", "modified"); - - PowerMockito.mockStatic(DashboardProperties.class); - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("os"); - - Collection<Service> items = deplList.items; - - Stream<Service> sampleStream = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream); - - String result = subject.getServicesByPage(mockedRequest); - assertTrue(result.contains("dti")); - - Mockito - .when(DashboardProperties.getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "auth")) - .thenReturn("auth"); - - Stream<Service> sampleStream2 = items.stream(); - Mockito.when(inventoryClient.getServices()).thenReturn(sampleStream2); - - String result2 = subject.getServicesByPage(mockedRequest); - assertTrue(result2.contains("dti")); - } @SuppressWarnings("unchecked") @Test @@ -670,38 +444,36 @@ public class InventoryControllerTest extends MockitoTestSuite { .thenThrow(BlueprintParseException.class).thenThrow(httpException) .thenThrow(Exception.class).thenReturn(null); - String actual1 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + String actual1 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); assertTrue(actual1.contains("error")); - String actual2 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + String actual2 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); assertTrue(actual2.contains("error")); - String actual3 = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + String actual3 = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); assertTrue(actual3.contains("error")); - String actual = subject.updateServiceTypeBlueprint(mockedRequest, bpItem); + String actual = subject.updateServiceTypeBlueprint(mockedRequest, bpItemFull); assertEquals(expected, actual); } @Test - public final void testDeleteService() throws Exception { - String expected = "{\"202\": \"OK\"}"; - doNothing().doThrow(serviceException).doThrow(Exception.class).when(inventoryClient) - .deleteService(Matchers.anyString()); - - String actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); - assertEquals(expected, actual); - - actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); - assertTrue(actual.contains("error")); - - actual = subject.deleteService("srvcId", mockedRequest, mockedResponse); - assertTrue(actual.contains("error")); - } - - @Test public final void testDeleteServiceType() throws Exception { - String expected = "{\"202\": \"OK\"}"; + //String expected = "{\"202\": \"OK\"}"; + String expected = "{\"204\": \"Blueprint deleted\"}"; + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); + deplForBp.clear(); + Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) + .thenReturn(deplForBp); + + List<ServiceRef> srvcRefList = new ArrayList<>(); + srvcRefList.clear(); + int itemCnt = 0; + ServiceRefList mockSvcRefList = new ServiceRefList(srvcRefList, itemCnt); + + Mockito.when(inventoryClient.getServicesForType(Matchers.<ServiceQueryParams>any())) + .thenReturn(mockSvcRefList); + doNothing().doThrow(serviceTypeException).doThrow(Exception.class).when(inventoryClient) .deleteServiceType(Matchers.anyString()); @@ -715,10 +487,24 @@ public class InventoryControllerTest extends MockitoTestSuite { assertTrue(actual.contains("error")); } + @Test + public final void testDeleteServiceType_withDepl() throws Exception { + CloudifyDeployedTenant mockCfyDeplTen = + new CloudifyDeployedTenant("id1", "tenant", "45435435", "54543534"); + + List<CloudifyDeployedTenant> deplForBp = new ArrayList<>(); + deplForBp.add(mockCfyDeplTen); + Mockito.when(cfyClient.getDeploymentForBlueprint(Matchers.<String>any())) + .thenReturn(deplForBp); + + String actual = subject.deleteServiceType("srvcId", mockedRequest, mockedResponse); + assertTrue(actual.contains("error")); + } + @SuppressWarnings("unchecked") @Test public final void testViewServiceTypeBlueprintContentById() throws Exception { - Optional<ServiceType> expected = Optional.of(bpItem); + Optional<ServiceType> expected = Optional.of(bpItemFull); when(inventoryClient.getServiceType(Matchers.anyString())).thenReturn(expected) .thenThrow(httpException).thenThrow(Exception.class); diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/model/ControllerOpsToolsTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/model/ControllerOpsToolsTest.java deleted file mode 100644 index 001df8d..0000000 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/model/ControllerOpsToolsTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * =============LICENSE_START========================================================= - * - * ================================================================================= - * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - *******************************************************************************/ -package org.onap.ccsdk.dashboard.model; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ControllerOpsToolsTest { - - ControllerOpsTools co; - private String id="123"; - private String url="http//google.com"; - - @Test - public void testControllerOpsTools() { - ControllerOpsTools co= new ControllerOpsTools(); - ControllerOpsTools co1= new ControllerOpsTools(id,url); - assertEquals("123",co1.getId()); - assertEquals("http//google.com",co1.getUrl()); - } - -} diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java index a5c5cf8..68223da 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/CloudifyRestClientImplTest.java @@ -31,8 +31,14 @@ import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Ignore; @@ -43,28 +49,32 @@ import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprint; -import org.onap.ccsdk.dashboard.model.CloudifyBlueprintList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant; -import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList; -import org.onap.ccsdk.dashboard.model.CloudifyDeployment; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentList; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateRequest; -import org.onap.ccsdk.dashboard.model.CloudifyDeploymentUpdateResponse; -import org.onap.ccsdk.dashboard.model.CloudifyEvent; -import org.onap.ccsdk.dashboard.model.CloudifyEventList; -import org.onap.ccsdk.dashboard.model.CloudifyEventList.Metadata; -import org.onap.ccsdk.dashboard.model.CloudifyExecution; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionList; -import org.onap.ccsdk.dashboard.model.CloudifyExecutionRequest; -import org.onap.ccsdk.dashboard.model.CloudifyNodeId; -import org.onap.ccsdk.dashboard.model.CloudifyNodeIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstance; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceId; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceIdList; -import org.onap.ccsdk.dashboard.model.CloudifyNodeInstanceList; -import org.onap.ccsdk.dashboard.model.CloudifyTenantList; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite; +import org.onap.ccsdk.dashboard.core.MockitoTestSuite.MockHttpServletRequestWrapper; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprint; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyBlueprintList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenant; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployedTenantList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeploymentList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEvent; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyEventList.Metadata; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecution; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyExecutionRequest; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeId; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstance; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceId; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceIdList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyNodeInstanceList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPlugin; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyPluginList; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyTenantList; import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -83,23 +93,27 @@ import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; @RunWith(PowerMockRunner.class) @PrepareForTest({DashboardProperties.class}) -public class CloudifyRestClientImplTest { +public class CloudifyRestClientImplTest extends MockitoTestSuite { @Mock RestTemplate mockRest; @InjectMocks CloudifyRestClientImpl subject = new CloudifyRestClientImpl(); - - protected final ObjectMapper objectMapper = new ObjectMapper(); + + HttpServletRequest mockedRequest; + HttpServletResponse mockedResponse; + protected final static ObjectMapper objectMapper = new ObjectMapper(); @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); objectMapper.registerModule(new Jdk8Module()); PowerMockito.mockStatic(DashboardProperties.class); - when(DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_URL)).thenReturn("https://orcl.com"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL)).thenReturn("https://orcl.com"); + CacheManager testCache = new CacheManager(); + subject.setCacheManager(testCache); this.subject.init(); } @@ -288,31 +302,10 @@ public class CloudifyRestClientImplTest { } @Test - public final void testGetTenantInfoFromDeploy() { - - CloudifyDeployedTenant cldDeplTenant = new CloudifyDeployedTenant("id1", "bp1", "tenant1"); - List<CloudifyDeployedTenant> cldDeplTenantItems = new ArrayList<CloudifyDeployedTenant>(); - cldDeplTenantItems.add(cldDeplTenant); - CloudifyDeployedTenantList cldDeployedTenantList = - new CloudifyDeployedTenantList(cldDeplTenantItems, null); - - ResponseEntity<CloudifyDeployedTenantList> response = - new ResponseEntity<CloudifyDeployedTenantList>(cldDeployedTenantList, HttpStatus.OK); - - when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<CloudifyDeployedTenantList>>any())) - .thenReturn(response); - - CloudifyDeployedTenantList actualResults = subject.getTenantInfoFromDeploy("tenant1"); - assertTrue(actualResults.items.get(0).blueprint_id.equals("bp1")); - } - - @Test public void testGetExecutions() { CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, + "bp1", "id1","tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -336,8 +329,8 @@ public class CloudifyRestClientImplTest { @Test public void testGetExecutionsSummary() { CloudifyExecution cldExecution = - new CloudifyExecution("successful", "created_at", "install", false, "bp1", "id1", - "tenant1", "error", "execution_id1", null, false, false); + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); @@ -361,8 +354,8 @@ public class CloudifyRestClientImplTest { @Test public void testStartExecution() { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "ended-at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -378,29 +371,10 @@ public class CloudifyRestClientImplTest { } @Test - public void testUpdateDeployment() { - CloudifyDeploymentUpdateRequest cfyDeployUpdateReq = - new CloudifyDeploymentUpdateRequest("deployment_id", "update", false, false, - "node_instance_id1", "4", "1000", "image", 2, "my_container"); - - CloudifyDeploymentUpdateResponse cfyDeployUpdateResp = new CloudifyDeploymentUpdateResponse( - "terminated", "created_at", "update", false, "blueprint_id", "deployment_id", "", "id1", - null, "tenant1", "junit", false, "resource_availability"); - - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<CloudifyDeploymentUpdateResponse>>any())) - .thenReturn(cfyDeployUpdateResp); - - CloudifyDeploymentUpdateResponse actualResult = - subject.updateDeployment(cfyDeployUpdateReq); - assertTrue(actualResult.status.equals("terminated")); - } - - @Test @Ignore public void testCancelExecution() { - CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "install", - false, "bp1", "id1", "tenant1", "error", "execution_id1", null, false, false); + CloudifyExecution cfyExecObj = new CloudifyExecution("successful", "created_at", "end_at", "install", + false, "bp1", "id1", "tenant1", "error", "execution_id1", null); Map<String, Object> params = new HashMap<String, Object>(); params.put("key1", "value1"); @@ -421,7 +395,6 @@ public class CloudifyRestClientImplTest { } @Test - @Ignore public void testGetBlueprint() { CloudifyBlueprint cldBp = new CloudifyBlueprint("file1", "description1", "343242", "3423423", "id1", null); @@ -441,16 +414,39 @@ public class CloudifyRestClientImplTest { doReturn(response).when(mockRest).exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<CloudifyBlueprintList>>any()); + Matchers.<ParameterizedTypeReference<CloudifyBlueprintList>>any()); CloudifyBlueprintList actualResult = subject.getBlueprint("id1", "tenant1"); assertTrue(actualResult.items.get(0).id.equals("id1")); } @Test - @Ignore public void testGetDeployments() { + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) + .thenReturn(response); + + CloudifyDeploymentList actualResult = subject.getDeployments("tenant", 10, 0); + assertTrue(actualResult.items.get(0).id.equals("id")); + } + + @Test + public void testGetDeployments_from_cache() { CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); @@ -466,11 +462,380 @@ public class CloudifyRestClientImplTest { ResponseEntity<CloudifyDeploymentList> response = new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); - when(mockRest.exchange(Matchers.contains("deploy"), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<Class<CloudifyDeploymentList>>any())) + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) .thenReturn(response); + + List<CloudifyDeployment> actualResult = subject.getDeployments("tenant", 10, 0, true, true); + assertTrue(actualResult.get(0).id.equals("id")); + } + + @Test + public void testGetDeploymentForBlueprint() { + CloudifyDeployedTenant cfyDepTenant = + new CloudifyDeployedTenant("id", "tenant", "created_at", "updated_at"); + List<CloudifyDeployedTenant> cfyDepTenantList = new ArrayList<>(); + cfyDepTenantList.add(cfyDepTenant); + + CloudifyDeployedTenantList.Metadata.Pagination pageObj = + new CloudifyDeployedTenantList.Metadata.Pagination(1, 0, 1); + CloudifyDeployedTenantList.Metadata metadata = new CloudifyDeployedTenantList.Metadata(pageObj); + + CloudifyDeployedTenantList cldDeployList = new CloudifyDeployedTenantList(cfyDepTenantList, metadata); - CloudifyDeploymentList actualResult = subject.getDeployments(); + ResponseEntity<CloudifyDeployedTenantList> response = + new ResponseEntity<CloudifyDeployedTenantList>(cldDeployList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyDeployedTenantList>>any())) + .thenReturn(response); + + List<CloudifyDeployedTenant> actuals = subject.getDeploymentForBlueprint("bpId"); + assertTrue(actuals.get(0).id.equals("id")); + } + + @Test + public void testGetDeploymentResource() { + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) + .thenReturn(response); + + CloudifyDeployment actualResult = subject.getDeploymentResource("id", "tenant"); + assertTrue(actualResult.id.equals("id")); + } + + @Test + public void testGetNodeInstanceDetails() { + CloudifyNodeInstance cfyNodeInstance = new CloudifyNodeInstance("id1", null); + + List<CloudifyNodeInstance> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstance>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceList cfyNodeInstList = + new CloudifyNodeInstanceList(cfyNodeInstanceItems, null); + + ResponseEntity<CloudifyNodeInstanceList> response2 = + new ResponseEntity<CloudifyNodeInstanceList>(cfyNodeInstList, HttpStatus.OK); + when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceList>>any())) + .thenReturn(response2); + + CloudifyNodeInstanceList actualResult = + subject.getNodeInstanceDetails("id", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("id1")); + } + + @Test + public void testGetNodeInstances() { + CloudifyNodeInstanceId cfyNodeInstance = new CloudifyNodeInstanceId("id1"); + + List<CloudifyNodeInstanceId> cfyNodeInstanceItems = new ArrayList<CloudifyNodeInstanceId>(); + cfyNodeInstanceItems.add(cfyNodeInstance); + + CloudifyNodeInstanceIdList cfyNodeInstList = + new CloudifyNodeInstanceIdList(cfyNodeInstanceItems, null); + + ResponseEntity<CloudifyNodeInstanceIdList> response2 = + new ResponseEntity<CloudifyNodeInstanceIdList>(cfyNodeInstList, HttpStatus.OK); + when(mockRest.exchange(Matchers.contains("node-instances"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyNodeInstanceIdList>>any())) + .thenReturn(response2); + + CloudifyNodeInstanceIdList actualResult = + subject.getNodeInstances("id", "tenant"); + assertTrue(actualResult.items.get(0).id.equals("id1")); + } + + + @Test + public void testGetExecutionsSummaryPerTenant() { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + ResponseEntity<CloudifyExecutionList> response = + new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) + .thenReturn(response); + + CloudifyExecutionList actualResult = + subject.getExecutionsSummaryPerTenant("tenant1"); + assertTrue(actualResult.items.get(0).id.contains("id1")); + } + + @Test + public void testGetExecutionIdSummary() { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + ResponseEntity<CloudifyExecution> response = + new ResponseEntity<CloudifyExecution>(cldExecution, HttpStatus.OK); + when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyExecution>>any())) + .thenReturn(response); + CloudifyExecution actuals = subject.getExecutionIdSummary("execution_id1", "tenant"); + assertTrue(actuals.id.contains("execution_id1")); + } + + @Test + public void testGetInstallExecutionSummary() { + CloudifyExecution cldExecution = + new CloudifyExecution("successful", "created_at", "ended_at", "install", false, "bp1", "id1", + "tenant1", "error", "execution_id1", null); + + List<CloudifyExecution> cldExecutionList = new ArrayList<CloudifyExecution>(); + + cldExecutionList.add(cldExecution); + + CloudifyExecutionList cloudifyExecutionList = + new CloudifyExecutionList(cldExecutionList, null); + + ResponseEntity<CloudifyExecutionList> response = + new ResponseEntity<CloudifyExecutionList>(cloudifyExecutionList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.contains("include"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyExecutionList>>any())) + .thenReturn(response); + + CloudifyExecutionList actualResult = + subject.getInstallExecutionSummary("id1", "tenant1"); + assertTrue(actualResult.items.get(0).id.contains("id1")); + } + + @Test + public void testViewBlueprint() { + byte[] outArr = "Any String you want".getBytes(); + ResponseEntity<byte[]> response = + new ResponseEntity<byte[]>(outArr, HttpStatus.OK); + + doReturn(response).when(mockRest).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<?>>any()); + + subject.viewBlueprint("tenant1", "id1"); + } + + @Test + public void testGetDeploymentNamesWithFilter() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + //mockedRequest.addParameter("filters", filterStr); + //mockedRequest.addParameter("sort", "name"); + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + String tenantsList = + "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + ResponseEntity<CloudifyTenantList> response1 = + new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); + + + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response2 = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + Mockito + .when(mockRest.exchange(Matchers.contains("tenants"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) + .thenReturn(response1); + + Mockito.when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) + .thenReturn(response2); + + List<String> actual = subject.getDeploymentNamesWithFilter(mockedRequest); + assertTrue(actual.size() > 0); + } + + @Test + public void testGetDeploymentsWithFilter() throws Exception { + MockHttpServletRequestWrapper mockedRequest = getMockedRequest(); + //mockedRequest.addParameter("filters", filterStr); + //mockedRequest.addParameter("sort", "name"); + Set<String> userRoleSet = new HashSet<String>(); + Set<String> userApps = new TreeSet<>(); + userRoleSet.add("Standard User"); + userRoleSet.add("ECOMPC_DCAE_WRITE"); + userApps.add("dcae"); + + Mockito.when(mockedRequest.getAttribute("userRoles")).thenReturn(userRoleSet); + Mockito.when(mockedRequest.getAttribute("userApps")).thenReturn(userApps); + + String tenantsList = + "{\"items\": [{\"id\": 1, \"dName\": null, \"name\": \"default_tenant\"}, {\"id\": 2, \"dName\": null, \"name\": \"dyh1b1902\"}], \"metadata\": {\"pagination\": {\"total\": 2, \"offset\": 0, \"size\": 0}}}"; + CloudifyTenantList sampleData = null; + try { + sampleData = objectMapper.readValue(tenantsList, CloudifyTenantList.class); + } catch (Exception e) { + } + + ResponseEntity<CloudifyTenantList> response1 = + new ResponseEntity<CloudifyTenantList>(sampleData, HttpStatus.OK); + + + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response2 = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + Mockito + .when(mockRest.exchange(Matchers.contains("tenants"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyTenantList>>any())) + .thenReturn(response1); + + Mockito.when(mockRest.exchange(Matchers.contains("deployments"), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) + .thenReturn(response2); + + List<CloudifyDeployment> actuals = subject.getDeploymentsWithFilter(mockedRequest); + assertTrue(actuals.size() > 0); + } + + @Test + public void testGetSecret() { + String secretTokenStr = + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + CloudifySecret sampleData = null; + try { + sampleData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); + } catch (Exception e) { + + } + + ResponseEntity<CloudifySecret> response = + new ResponseEntity<CloudifySecret>(sampleData, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifySecret>>any())) + .thenReturn(response); + + CloudifySecret actuals = subject.getSecret("acl_key", "tenant"); + assertTrue(actuals.getKey().equals("acl_key")); + } + + @Test + public void testDeleteBlueprint() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyBlueprint>>any())).thenReturn(null); + subject.deleteBlueprint("bp", "tenant"); + } + + @Test + public void testGetPlugins() { + CloudifyPlugin sampleData = + new CloudifyPlugin("plugin1", "202001", "linux", "linux_k8s_plugin", "20200801"); + + List<CloudifyPlugin> cfyPlugins = new ArrayList<CloudifyPlugin>(); + cfyPlugins.add(sampleData); + + CloudifyPluginList.Metadata.Pagination pageObj = + new CloudifyPluginList.Metadata.Pagination(1, 0, 1); + CloudifyPluginList.Metadata metadata = new CloudifyPluginList.Metadata(pageObj); + + CloudifyPluginList cfyPluginList = new CloudifyPluginList(cfyPlugins, metadata); + ResponseEntity<CloudifyPluginList> response = + new ResponseEntity<CloudifyPluginList>(cfyPluginList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifyPluginList>>any())) + .thenReturn(response); + + CloudifyPluginList actuals = subject.getPlugins(); + assertTrue(actuals.items.get(0).package_name.equals("plugin1")); + } + + @Test + public void testGetDeploymentInputs() { + CloudifyDeployment cldDeployment = new CloudifyDeployment("description", "blueprint_id", + "created_at", "updated_at", "id", null, null, null, null, null, null, null, "tenant"); + + List<CloudifyDeployment> cfyDeployItems = new ArrayList<CloudifyDeployment>(); + cfyDeployItems.add(cldDeployment); + + CloudifyDeploymentList.Metadata.Pagination pageObj = + new CloudifyDeploymentList.Metadata.Pagination(1, 0, 1); + CloudifyDeploymentList.Metadata metadata = new CloudifyDeploymentList.Metadata(pageObj); + + CloudifyDeploymentList cldDeployList = new CloudifyDeploymentList(cfyDeployItems, metadata); + + ResponseEntity<CloudifyDeploymentList> response = + new ResponseEntity<CloudifyDeploymentList>(cldDeployList, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<CloudifyDeploymentList>>any())) + .thenReturn(response); + + CloudifyDeploymentList actualResult = subject.getDeploymentInputs("id", "tenant"); assertTrue(actualResult.items.get(0).id.equals("id")); } + + } + diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java index f90afa9..7d85196 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/ConsulRestClientImplTest.java @@ -23,26 +23,30 @@ package org.onap.ccsdk.dashboard.rest; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Mockito.when; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import org.json.JSONObject; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.ccsdk.dashboard.model.ConsulDatacenter; -import org.onap.ccsdk.dashboard.model.ConsulNodeInfo; -import org.onap.ccsdk.dashboard.model.ConsulServiceHealth; -import org.onap.ccsdk.dashboard.model.ConsulServiceInfo; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifySecret; +import org.onap.ccsdk.dashboard.model.consul.ConsulDatacenter; +import org.onap.ccsdk.dashboard.model.consul.ConsulDeploymentHealth; +import org.onap.ccsdk.dashboard.model.consul.ConsulNodeInfo; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceHealth; +import org.onap.ccsdk.dashboard.model.consul.ConsulServiceInfo; import org.onap.ccsdk.dashboard.util.DashboardProperties; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -64,22 +68,36 @@ public class ConsulRestClientImplTest { @Mock RestTemplate mockRest; - + @InjectMocks - ConsulRestClientImpl subject = new ConsulRestClientImpl(); + ConsulRestClientImpl subject; + + String[] svcTags = {"cfytenantname=onap"}; + + protected final static ObjectMapper objectMapper = new ObjectMapper(); + static HttpClientErrorException httpException; - protected final ObjectMapper objectMapper = new ObjectMapper(); - HttpClientErrorException httpException; + @BeforeClass + public static void setUpBeforeClass() throws Exception { + httpException = new HttpClientErrorException(HttpStatus.FORBIDDEN, "statusText"); + objectMapper.registerModule(new Jdk8Module()); + } + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - objectMapper.registerModule(new Jdk8Module()); - httpException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "statusText"); PowerMockito.mockStatic(DashboardProperties.class); - when(DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_CONSUL_URL)).thenReturn("https://invt.com"); - this.subject.init(); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CONSUL_URL)).thenReturn("https://cnsl-svc.com"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL)).thenReturn("https://orcl-svc.com"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME)).thenReturn("admin"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS)).thenReturn("admin"); + subject.setConsul_acl_token("consul_acl_token_for_dash"); + subject.init(); } @After @@ -87,13 +105,54 @@ public class ConsulRestClientImplTest { } @Test + public final void testGetConsulAcl() { + String secretTokenStr = + "{\"created_at\": \"created_ts\", \"key\": \"acl_key\", \"updated_at\": \"updated_ts\", \"value\": \"acl_token_val\", \"visibility\": \"global\", \"is_hidden_value\": \"false\", \"tenant_name\": \"tenant\", \"resource_availability\": \"rsrc\"}"; + CloudifySecret sampleData = null; + try { + sampleData = objectMapper.readValue(secretTokenStr, CloudifySecret.class); + } catch (Exception e) { + } + + ResponseEntity<CloudifySecret> response = + new ResponseEntity<CloudifySecret>(sampleData, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<CloudifySecret>>any())) + .thenReturn(response); + String actualSecretStr = subject.getConsulAcl(mockRest); + assertTrue(actualSecretStr.equals("acl_token_val")); + } + + @Test(expected = Exception.class) + public final void testCreateCfyRestTemplate() throws Exception { + String webapiUrl = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_URL); + String user = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_USERNAME); + String pass = DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_CLOUDIFY_PASS); + URL url = null; + try { + url = new URL(webapiUrl); + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + String urlScheme = webapiUrl.split(":")[0]; + subject.createCfyRestTemplate(url, user, pass, urlScheme); + } + + @Test public final void testGetServiceHealth() { ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", - "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", - "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + "OK Output:", + "pgaas1_Service_ID", "pgaasServer1", svcTags, 34234, 4234); + // new ConsulServiceHealth() List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); @@ -109,21 +168,47 @@ public class ConsulRestClientImplTest { assertTrue(actualCnslSrvcHlth.get(0).node.equals("cjlvmcnsl00")); } + @Test(expected = Exception.class) + public final void get_svc_health_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenThrow(httpException); + + subject.getServiceHealth("dc1", "srvc1"); + } + + @Test(expected = Exception.class) + public final void get_services_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<Map<String, Object>>>any())) + .thenThrow(httpException); + subject.getServices("dc1"); + } + @Test - @Ignore public final void testGetServices() { List<String> srvcIps = new ArrayList<String>(); srvcIps.add("135.91.224.136"); srvcIps.add("135.91.224.138"); ConsulServiceInfo consulSrvcInfo = new ConsulServiceInfo("pgaasServer1", srvcIps); + Map<String, Object> respObj = new HashMap<String, Object>(); + respObj.put("pgaasServer1", srvcIps); + List<ConsulServiceInfo> expectedCnslSrvcs = new ArrayList<ConsulServiceInfo>(); expectedCnslSrvcs.add(consulSrvcInfo); - // ResponseEntity<Map<String, Object>> response = new ResponseEntity<Map<String, - // Object>>(consulSrvcInfo); + ResponseEntity<Map<String, Object>> response = + new ResponseEntity<Map<String,Object>>(respObj, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<Map<String, Object>>>any())).thenReturn(response); - subject.getServices("dc1"); + List<ConsulServiceInfo> actualSvcList = subject.getServices("dc1"); + assertTrue(actualSvcList.get(0).name.equals("pgaasServer1")); } @Test @@ -146,13 +231,22 @@ public class ConsulRestClientImplTest { } + @Test(expected = Exception.class) + public final void get_nodes_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulNodeInfo>>>any())) + .thenThrow(httpException); + subject.getNodes("dc1"); + } + @Test public final void testGetNodeServicesHealth() { ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", "This is a pgaas1_Service_ID health check", "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", - "pgaas1_Service_ID", "pgaasServer1", 190199, 199395); + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); expectedCnslSrvcHlth.add(consulSrvcHlth); @@ -170,6 +264,15 @@ public class ConsulRestClientImplTest { assertTrue(actualNodeHlthList.get(0).node.equals("cjlvmcnsl00")); } + @Test(expected = Exception.class) + public final void get_node_svc_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenThrow(httpException); + subject.getNodeServicesHealth("dc1", "nodeId1"); + } + @Test public final void testGetDatacenters() { ConsulDatacenter cnslDc = new ConsulDatacenter("dc1"); @@ -189,24 +292,45 @@ public class ConsulRestClientImplTest { assertTrue(actualDcList.get(0).name.equals("dc1")); } - @Test - @Ignore - public final void testRegisterService() { - fail("Not yet implemented"); // TODO + @Test(expected = Exception.class) + public final void get_dc_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<String>>>any())) + .thenThrow(httpException); + subject.getDatacenters(); } - + @Test - public final void testDeregisterService() { + public final void testGetServiceHealthByDeploymentId() { + ConsulServiceHealth consulSrvcHlth = new ConsulServiceHealth("cjlvmcnsl00", + "service:pgaas1_Service_ID", "Service 'pgaasServer1' check", "passing", + "This is a pgaas1_Service_ID health check", + "HTTP GET http://srvc.com:8000/healthcheck/status: 200 OK Output: { \"output\": \"Thu Apr 20 19:53:01 UTC 2017|INFO|masters=1 pgaas1.com|secondaries=0 |maintenance= |down=1 pgaas2.com| \" }\n", + "pgaas1_Service_ID", "pgaasServer1", svcTags, 190199, 199395); - JSONObject jsonResp = new JSONObject(); + List<ConsulServiceHealth> expectedCnslSrvcHlth = new ArrayList<ConsulServiceHealth>(); + expectedCnslSrvcHlth.add(consulSrvcHlth); - ResponseEntity<JSONObject> result = new ResponseEntity<JSONObject>(jsonResp, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<JSONObject>>any())) - .thenReturn(result); + ResponseEntity<List<ConsulServiceHealth>> response = + new ResponseEntity<List<ConsulServiceHealth>>(expectedCnslSrvcHlth, HttpStatus.OK); - int actualCode = subject.deregisterService("service1"); - assertTrue(actualCode == 200); - } + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenReturn(response); + ConsulDeploymentHealth cdh = subject.getServiceHealthByDeploymentId("deploymentId"); + assertTrue(cdh.getNode().equals("cjlvmcnsl00")); + } + + @Test(expected = Exception.class) + public final void get_svc_health_by_depId_rest_client_exception() { + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<List<ConsulServiceHealth>>>any())) + .thenThrow(httpException); + subject.getServiceHealthByDeploymentId("deploymentId"); + } + } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java index 7bd085b..2024d72 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/DeploymentHandlerClientImplTest.java @@ -36,17 +36,20 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.onap.ccsdk.dashboard.exceptions.BadRequestException; import org.onap.ccsdk.dashboard.exceptions.DeploymentNotFoundException; import org.onap.ccsdk.dashboard.exceptions.DownstreamException; import org.onap.ccsdk.dashboard.exceptions.ServerErrorException; import org.onap.ccsdk.dashboard.exceptions.ServiceAlreadyExistsException; +import org.onap.ccsdk.dashboard.model.cloudify.CloudifyDeployment; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentLink; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentRequest; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponse; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentResponseLinks; import org.onap.ccsdk.dashboard.model.deploymenthandler.DeploymentsListResponse; import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -66,16 +69,21 @@ public class DeploymentHandlerClientImplTest { @Mock RestTemplate mockRest; + @Mock + CloudifyClient cfyClient; + @InjectMocks DeploymentHandlerClientImpl subject; @Before public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); PowerMockito.mockStatic(DashboardProperties.class); - when(DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_DHANDLER_URL)).thenReturn("https://dplh.com"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_DHANDLER_URL)).thenReturn("https://dplh.com"); + CacheManager testCache = new CacheManager(); + subject.setCacheManager(testCache); this.subject.init(); - } @After @@ -83,6 +91,21 @@ public class DeploymentHandlerClientImplTest { } @Test + public final void testCheckHealth() { + String expectStr = "DH mS health check"; + ResponseEntity<String> response = + new ResponseEntity<String>(expectStr, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<String>>any())).thenReturn(response) + .thenReturn(response); + + String actualStr = subject.checkHealth(); + assertTrue(actualStr.equals(expectStr)); + } + + @Test public final void testGetDeployments() { Collection<DeploymentLink> expectedDeplRefs = new ArrayList<DeploymentLink>(); expectedDeplRefs.add(new DeploymentLink("http://dplh.com/dpl1")); @@ -206,93 +229,6 @@ public class DeploymentHandlerClientImplTest { } @Test - public final void testUpdateDeployment() throws Exception { - DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); - - DeploymentResponseLinks newDeplItemLink = - new DeploymentResponseLinks("selfUrl", "statusUrl"); - DeploymentResponse expectedDeplItem = new DeploymentResponse("req1", newDeplItemLink); - - ResponseEntity<DeploymentResponse> response = - new ResponseEntity<DeploymentResponse>(expectedDeplItem, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); - - DeploymentResponse actualResponse = subject.updateDeployment("dpl12", "tenant12", deplReq); - assertTrue(actualResponse.getRequestId().equals("req1")); - } - - @Test(expected = DownstreamException.class) - public final void testUpdateDeployment_downstreamError() throws Exception { - - DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); - - HttpServerErrorException httpException = - new HttpServerErrorException(HttpStatus.BAD_GATEWAY, "statusText"); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) - .thenThrow(httpException); - - subject.updateDeployment("dpl12", "tenant12", deplReq); - - } - - @Test(expected = BadRequestException.class) - public final void testUpdateDeployment_badReqError() throws Exception { - - DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); - - HttpClientErrorException httpException = - new HttpClientErrorException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "statusText"); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) - .thenThrow(httpException); - - subject.updateDeployment("dpl12", "tenant12", deplReq); - - } - - @Test(expected = ServiceAlreadyExistsException.class) - public final void testUpdateDeployment_srvcExistError() throws Exception { - - DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); - - HttpClientErrorException httpException = - new HttpClientErrorException(HttpStatus.CONFLICT, "statusText"); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) - .thenThrow(httpException); - - subject.updateDeployment("dpl12", "tenant12", deplReq); - - } - - @Test(expected = ServerErrorException.class) - public final void testUpdateDeployment_srvcError() throws Exception { - - DeploymentRequest deplReq = new DeploymentRequest("serviceTypeId", null); - - HttpServerErrorException httpException = - new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "statusText"); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())) - .thenThrow(httpException); - - subject.updateDeployment("dpl12", "tenant12", deplReq); - - } - - @Test public final void testDeleteDeployment() throws Exception { DeploymentResponseLinks newDeplItemLink = new DeploymentResponseLinks("selfUrl", "statusUrl"); @@ -305,6 +241,12 @@ public class DeploymentHandlerClientImplTest { Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<DeploymentResponse>>any())).thenReturn(response); + CloudifyDeployment cfyDepl = + new CloudifyDeployment("description", "blueprint_id", "created_at", "updated_at", + "id", null, null, null, null, null, null, null, "tenant_name"); + + when(cfyClient.getDeploymentResource(Matchers.anyString(), Matchers.anyString())).thenReturn(cfyDepl); + subject.deleteDeployment("deploymentId", "tenant"); } diff --git a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java index d4c5e14..e0452d0 100644 --- a/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java +++ b/ccsdk-app-common/src/test/java/org/onap/ccsdk/dashboard/rest/RestInventoryClientImplTest.java @@ -30,6 +30,9 @@ import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.stream.Stream; @@ -52,7 +55,11 @@ import org.onap.ccsdk.dashboard.model.inventory.ServiceType; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeList; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams; import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeServiceMap; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummary; +import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeSummaryList; import org.onap.ccsdk.dashboard.util.DashboardProperties; +import org.onap.portalsdk.core.util.CacheManager; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -84,9 +91,13 @@ public class RestInventoryClientImplTest { ServiceList deplListNext = null; Service deplItem = null; - ServiceType bpItem = null; - ServiceTypeList bpList = null; - ServiceTypeList bpListNext = null; + ServiceTypeSummary bpItem, bpItem2 = null; + ServiceTypeSummaryList bpList, bpList2 = null; + + ServiceType bpItemFull = null; + ServiceTypeList bpItemFullList = null; + + ServiceTypeSummaryList bpListNext = null; ServiceTypeRequest bpUploadItem = null; @@ -94,11 +105,13 @@ public class RestInventoryClientImplTest { public void setUp() throws Exception { MockitoAnnotations.initMocks(this); objectMapper.registerModule(new Jdk8Module()); - getExpectedBueprints(); + getExpectedBlueprints(); getExpectedDeployments(); PowerMockito.mockStatic(DashboardProperties.class); - when(DashboardProperties.getControllerProperty("dev", - DashboardProperties.CONTROLLER_SUBKEY_INVENTORY_URL)).thenReturn("https://invt.com"); + when(DashboardProperties.getControllerProperty("site.primary", + DashboardProperties.SITE_SUBKEY_INVENTORY_URL)).thenReturn("https://invt.com"); + CacheManager testCache = new CacheManager(); + subject.setCacheManager(testCache); this.subject.init(); } @@ -122,96 +135,124 @@ public class RestInventoryClientImplTest { ServiceList.PaginationLinks paginationLinks2 = objectMapper.readValue(pageLinks2, ServiceList.PaginationLinks.class); - int totalCount = 2; - deplList = new ServiceList(items, totalCount, paginationLinks); + int totalCount = 1; + deplList = new ServiceList(items, totalCount, paginationLinks2); deplListNext = new ServiceList(items, totalCount, paginationLinks2); } - - public void getExpectedBueprints() + + public void getExpectedBlueprints() throws JsonParseException, JsonMappingException, IOException { - bpItem = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, + + bpItem = new ServiceTypeSummary.Builder().application("app1").component("comp1"). + typeName("xyz1731-helm-1906").owner("xyz1731").typeVersion(1906).build(); + + bpItem2 = new ServiceTypeSummary("xyz1731", "xyz1731-helm-1906", 1906, "app1", "comp1", "123-456-789", + "342343", true); + bpItemFull = new ServiceType.Builder("xyz1731", "xyz1731-helm-1906", 1906, "tosca_definitions_version: cloudify_dsl_1_3", "", "app1", "comp1").build(); - Collection<ServiceType> items = new ArrayList<ServiceType>(); - items.add(bpItem); + Collection<ServiceTypeSummary> items = new ArrayList<ServiceTypeSummary>(); + items.add(bpItem); + Collection<ServiceTypeSummary> items2 = new ArrayList<ServiceTypeSummary>(); + items2.add(bpItem2); + String pageLinks = - "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-services/?offset=25\"}}"; + "{\"previousLink\":null,\"nextLink\":{\"rel\":\"next\",\"href\":\"https://invt.com:30123/dcae-service-types/?offset=25\"}}"; String pageLinks2 = "{\"previousLink\":null,\"nextLink\":null}"; - ServiceTypeList.PaginationLinks paginationLinks = - objectMapper.readValue(pageLinks, ServiceTypeList.PaginationLinks.class); - ServiceTypeList.PaginationLinks paginationLinks2 = - objectMapper.readValue(pageLinks2, ServiceTypeList.PaginationLinks.class); + ServiceTypeSummaryList.PaginationLinks paginationLinks = + objectMapper.readValue(pageLinks, ServiceTypeSummaryList.PaginationLinks.class); + ServiceTypeSummaryList.PaginationLinks paginationLinks2 = + objectMapper.readValue(pageLinks2, ServiceTypeSummaryList.PaginationLinks.class); int totalCount = 2; - bpList = new ServiceTypeList(items, totalCount, paginationLinks); - bpListNext = new ServiceTypeList(items, totalCount, paginationLinks2); + bpList = new ServiceTypeSummaryList(items, totalCount, paginationLinks); + bpList2 = new ServiceTypeSummaryList(items2, totalCount, paginationLinks); + bpListNext = new ServiceTypeSummaryList(items, totalCount, paginationLinks2); } @Test - @Ignore - public final void testInit() { - fail("Not yet implemented"); // TODO + public final void testCheckHealth() { + String expectStr = "Inventory mS health check"; + ResponseEntity<String> response = + new ResponseEntity<String>(expectStr, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<String>>any())).thenReturn(response) + .thenReturn(response); + + String actualStr = subject.checkHealth(); + assertTrue(actualStr.equals(expectStr)); } @Test public final void testGetServiceTypes() { - /* - * String serviceTypeStr = - * "{\"paginationLinks\":{\"previousLink\":null,\"nextLink\":null}},\"totalCount\":32,\"items\":[{\"owner\":\"xyz1731\",\"typeName\":\"xyz1731-helm-1906\",\"typeVersion\":1906,\"blueprintTemplate\":\"tosca_definitions_version: cloudify_dsl_1_3\\nimports:\\n - http://www.getcloudify.org/spec/cloudify/4.2/types.yaml\\n - http://dockercentral.it.att.com:8093/nexus/repository/rawcentral/com.att.dcae.controller/type_files/helm/3.0.1/helm-type.yaml\\ninputs:\\n deployment-description:\\n default: ''\\n chart-name:\\n default: ''\\n tiller-server:\\n default: ''\\n tiller-server-port:\\n default: ''\\n namespace:\\n default: ''\\n chart-repo-url:\\n default: http://32.68.14.161/charts\\n chart-version :\\n default: ''\\n config-url:\\n default: ''\\n config-format:\\n default: ''\\n tls-enable:\\n description: enable helm TSL\\n type: boolean\\n default: false\\n config-dir:\\n description: config dir\\n type: string\\n default: '/opt/manager/resources/'\\n stable-repo-url:\\n description: URL for stable repository\\n type: string\\n default: 'http://32.68.14.161/stable'\\nnode_templates:\\n ecompcomponent:\\n type: onap.nodes.component\\n properties:\\n tiller-server-ip: { get_input: tiller-server }\\n tiller-server-port: { get_input: tiller-server-port }\\n component-name: { get_input: chart-name }\\n chart-repo-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: chart-repo-url } ] }\\n chart-version: { get_input: chart-version }\\n namespace: { get_input: namespace }\\n config-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: config-url } ] }\\n config-format: { get_input: config-format}\\n tls-enable: { get_input: tls-enable}\\n ca: { get_secret: ca_value}\\n cert: { get_secret: cert_value}\\n key: { get_secret: key_value}\\n config-dir: { get_input: config-dir}\\n stable-repo-url: { concat: [ 'http://', { get_secret: controller_helm_user }, ':', { get_secret: controller_helm_password }, '@', { get_input: stable-repo-url } ] }\\noutputs:\\n ecompcomponent-helm-output:\\n description: helm value and helm history\\n value:\\n helm-value: { get_attribute: [ecompcomponent, current-helm-value] }\\n helm-history: { get_attribute: [ecompcomponent, helm-history] }\",\"serviceIds\":[],\"vnfTypes\":[],\"serviceLocations\":[],\"asdcServiceId\":\"\",\"asdcResourceId\":\"\",\"asdcServiceURL\":null,\"application\":\"ECOMP\",\"component\":\"controller\",\"typeId\":\"72b8577a-5043-43ab-9aa5-6808b8f53967\",\"selfLink\":{\"rel\":\"self\",\"href\":\"https://ecompc-invt-dev-s5.ecomp.idns.cip.att.com:30123/dcae-service-types/72b8577a-5043-43ab-9aa5-6808b8f53967\"},\"created\":1551214264536,\"deactivated\":null}]" - * ; ServiceTypeList sampleData = null; try { sampleData = - * objectMapper.readValue(serviceTypeStr, ServiceTypeList.class); } catch - * (Exception e) { } - */ - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> expectedResult = items.stream(); - - ResponseEntity<ServiceTypeList> response = - new ResponseEntity<ServiceTypeList>(bpList, HttpStatus.OK); - - ResponseEntity<ServiceTypeList> response2 = - new ResponseEntity<ServiceTypeList>(bpListNext, HttpStatus.OK); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> expectedResult = items.stream(); + + ResponseEntity<ServiceTypeSummaryList> response = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); + + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeList>>any())).thenReturn(response) + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) .thenReturn(response2); - Stream<ServiceType> actualResult = subject.getServiceTypes(); + Stream<ServiceTypeSummary> actualResult = subject.getServiceTypes(); assertNotNull(actualResult); assertTrue(expectedResult.count() == actualResult.count()); } @Test + public final void testCacheServiceTypes() { + ResponseEntity<ServiceTypeSummaryList> response = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); + + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); + + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + .thenReturn(response2); + + subject.cacheServiceTypes(); + } + + @Test public final void testGetServiceTypesServiceTypeQueryParams() { ServiceTypeQueryParams qryParms = new ServiceTypeQueryParams.Builder() .asdcResourceId("asdcResourceId").asdcServiceId("asdcServiceId").onlyActive(true) .onlyLatest(false).serviceId("serviceId").serviceLocation("serviceLocation") .typeName("typeName").vnfType("vnfType").build(); - Collection<ServiceType> items = bpList.items; - Stream<ServiceType> expectedResult = items.stream(); + Collection<ServiceTypeSummary> items = bpList.items; + Stream<ServiceTypeSummary> expectedResult = items.stream(); - ResponseEntity<ServiceTypeList> response = - new ResponseEntity<ServiceTypeList>(bpList, HttpStatus.OK); + ResponseEntity<ServiceTypeSummaryList> response = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); - ResponseEntity<ServiceTypeList> response2 = - new ResponseEntity<ServiceTypeList>(bpListNext, HttpStatus.OK); + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ServiceTypeList>>any())).thenReturn(response) + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) .thenReturn(response2); - Stream<ServiceType> actualResult = subject.getServiceTypes(qryParms); + Stream<ServiceTypeSummary> actualResult = subject.getServiceTypes(qryParms); assertNotNull(actualResult); assertTrue(expectedResult.count() == actualResult.count()); } @Test public final void testGetServiceType() { - Optional<ServiceType> expectedResult = Optional.of(bpItem); + Optional<ServiceType> expectedResult = Optional.of(bpItemFull); ResponseEntity<ServiceType> response = - new ResponseEntity<ServiceType>(bpItem, HttpStatus.OK); + new ResponseEntity<ServiceType>(bpItemFull, HttpStatus.OK); when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceType>>any())) @@ -222,140 +263,87 @@ public class RestInventoryClientImplTest { } @Test - public final void testAddServiceTypeServiceType() { - - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<ServiceType>>any())).thenReturn(bpItem); - - ServiceType actualResult = subject.addServiceType(bpItem); - assertTrue(actualResult.getTypeName().contains("xyz")); - } - - @Test - public final void testAddServiceTypeServiceTypeRequest() { - ServiceTypeRequest srvcReq = ServiceTypeRequest.from(bpItem); - - when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), - Matchers.<Class<ServiceType>>any())).thenReturn(bpItem); - - ServiceType actualResult = subject.addServiceType(srvcReq); - assertTrue(actualResult.getTypeName().contains("xyz")); - } - - @Test - public final void testDeleteServiceType() throws Exception { - ResponseEntity<ApiResponseMessage> response = - new ResponseEntity<ApiResponseMessage>(HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), - Matchers.<HttpEntity<?>>any(), - Matchers.<ParameterizedTypeReference<ApiResponseMessage>>any())).thenReturn(response); - - subject.deleteServiceType("4243234"); - } - - @Test - public final void testGetServices() { - - Collection<Service> items = deplList.items; - Stream<Service> expectedResult = items.stream(); - + public final void testGetServicesForType() throws Exception { + String typeId = "44234234"; + ServiceRef expectedSrvc = new ServiceRef("dcae_dtiapi_1902", "432423", "433434"); + Collection<ServiceRef> expectedSrvcIds = new ArrayList<ServiceRef>(); + expectedSrvcIds.add(expectedSrvc); + ServiceRefList expectedSvcRefList = new ServiceRefList(expectedSrvcIds, 1); ResponseEntity<ServiceList> response = new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); - ResponseEntity<ServiceList> response2 = - new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) - .thenReturn(response).thenReturn(response2); - - Stream<Service> actualResult = subject.getServices(); - assertNotNull(actualResult); - assertTrue(expectedResult.count() == actualResult.count()); - - } - - @Test - public final void testGetServicesForType() { - ResponseEntity<ServiceList> response = - new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); - - ResponseEntity<ServiceList> response2 = - new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) - .thenReturn(response).thenReturn(response2); - ServiceQueryParams qryParms = new ServiceQueryParams.Builder().typeId("typeId").build(); - - ServiceRefList actualResult = subject.getServicesForType(qryParms); - assertTrue(actualResult.items.size() == 2); - ServiceRef actualSrvcItem = (ServiceRef) actualResult.items.toArray()[0]; - assertTrue(actualSrvcItem.getServiceId().contains("dtiapi")); - + .thenReturn(response); + + ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build(); + ServiceRefList actualSvcRefList = subject.getServicesForType(qryParams); + assertTrue(actualSvcRefList.totalCount == expectedSvcRefList.totalCount); } - + @Test - public final void testGetServicesServiceQueryParams() { - ServiceQueryParams qryParms = new ServiceQueryParams.Builder().typeId("typeId") - .vnfId("vnfId").vnfLocation("vnfLocation").vnfType("vnfType") - .componentType("componentType").shareable(false).created("43443423").build(); - - Collection<Service> items = deplList.items; - Stream<Service> expectedResult = items.stream(); - - ResponseEntity<ServiceList> response = - new ResponseEntity<ServiceList>(deplList, HttpStatus.OK); - - ResponseEntity<ServiceList> response2 = - new ResponseEntity<ServiceList>(deplListNext, HttpStatus.OK); - - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ServiceList>>any())) - .thenReturn(response).thenReturn(response2); + public final void testAddServiceTypeServiceType() { - Stream<Service> actualResult = subject.getServices(qryParms); - assertTrue(expectedResult.count() == actualResult.count()); - } + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<ServiceType>>any())).thenReturn(bpItemFull); - @Test - public final void testGetService() { - Optional<Service> expectedResult = Optional.of(deplItem); + ResponseEntity<ServiceTypeSummaryList> response = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); - ResponseEntity<Service> response = new ResponseEntity<Service>(deplItem, HttpStatus.OK); + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<Service>>any())) - .thenReturn(response); - - Optional<Service> actualResult = subject.getService("432432423"); - assertTrue( - expectedResult.get().getDeploymentRef().equals(actualResult.get().getDeploymentRef())); + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + .thenReturn(response2); + + ServiceType actualResult = subject.addServiceType(bpItemFull); + assertTrue(actualResult.getTypeName().contains("xyz")); } @Test - public final void testPutService() { + public final void testAddServiceTypeServiceTypeRequest() { + ServiceTypeRequest srvcReq = ServiceTypeRequest.from(bpItemFull); - ResponseEntity<Service> response = new ResponseEntity<Service>(deplItem, HttpStatus.OK); + when(mockRest.postForObject(Matchers.anyString(), Matchers.<HttpEntity<?>>any(), + Matchers.<Class<ServiceType>>any())).thenReturn(bpItemFull); + + ResponseEntity<ServiceTypeSummaryList> response = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); - when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), - Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<Service>>any())) - .thenReturn(response); + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - subject.putService("423423", deplItem); + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response) + .thenReturn(response2); + ServiceType actualResult = subject.addServiceType(srvcReq); + assertTrue(actualResult.getTypeName().contains("xyz")); } @Test - public final void testDeleteService() throws Exception { + public final void testDeleteServiceType() throws Exception { ResponseEntity<ApiResponseMessage> response = new ResponseEntity<ApiResponseMessage>(HttpStatus.OK); when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), Matchers.<HttpEntity<?>>any(), Matchers.<ParameterizedTypeReference<ApiResponseMessage>>any())).thenReturn(response); + + ResponseEntity<ServiceTypeSummaryList> response1 = + new ResponseEntity<ServiceTypeSummaryList>(bpList, HttpStatus.OK); + + ResponseEntity<ServiceTypeSummaryList> response2 = + new ResponseEntity<ServiceTypeSummaryList>(bpListNext, HttpStatus.OK); - subject.deleteService("4243234"); + when(mockRest.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<?>>any(), + Matchers.<ParameterizedTypeReference<ServiceTypeSummaryList>>any())).thenReturn(response1) + .thenReturn(response2); + + subject.deleteServiceType("4243234"); } } |