diff options
author | 2020-09-23 20:30:23 +0000 | |
---|---|---|
committer | 2020-09-23 20:30:23 +0000 | |
commit | 834f5db267860396e3fd3ed1529abf37bd299b4c (patch) | |
tree | d04bcb53d8296a446d8a5a7aa2abf44295e0cb72 /mod2/catalog-service/src/test | |
parent | d1d83ea8dfcd7c4dd943482bc93e9b699ffaabd8 (diff) | |
parent | dd74c5ec9c4761de2bec19f9fb53bba36c7c6c2c (diff) |
Merge "adding catalog-service for mod2"
Diffstat (limited to 'mod2/catalog-service/src/test')
24 files changed, 3054 insertions, 0 deletions
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/BaseMsObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/BaseMsObjectMother.java new file mode 100644 index 0000000..fc57442 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/BaseMsObjectMother.java @@ -0,0 +1,131 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.objectmothers; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsLocation; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsStatus; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsType; +import org.onap.dcaegen2.platform.mod.model.common.AuditFields; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceUpdateRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.*; + +public class BaseMsObjectMother { + + public static final String BASE_MS_NAME = "ms-1"; + public static final String BASE_MS_ID = "id123"; + public static final BaseMsType BASE_MS_TYPE = BaseMsType.TICK; + public static final BaseMsLocation LOCATION = BaseMsLocation.CENTRAL; + public static final String NAMESPACE = "sam.collector.namespace"; + public static final String NOTE = "Sample Note"; + public static final String LABEL_1 = "mylabel1"; + public static final String LABEL_2 = "mylabel2"; + public static final String USER = "abc123"; + private static final String BASE_MS_TAG = "sample-ms-tag" ; + private static final String BASE_MS_SERVICE_NAME = "sample-core"; + + + public static MicroserviceCreateRequest createMockMsRequest() { + Map<String, Object> metadata = new HashMap(); + metadata.put("notes", NOTE); + metadata.put("labels", Arrays.asList(LABEL_1, LABEL_2)); + + MicroserviceCreateRequest request = new MicroserviceCreateRequest(); + request.setName(BASE_MS_NAME); + request.setTag(BASE_MS_TAG); + request.setServiceName(BASE_MS_SERVICE_NAME); + request.setType(BASE_MS_TYPE); + request.setLocation(LOCATION); + request.setNamespace(NAMESPACE); + request.setMetadata(metadata); + request.setUser(USER); + + return request; + } + + public static BaseMicroservice createMockMsObject() { + BaseMicroservice microservice = new BaseMicroservice(); + microservice.setId(BASE_MS_ID); + microservice.setName(BASE_MS_NAME); + microservice.setServiceName(BASE_MS_SERVICE_NAME); + microservice.setTag(BASE_MS_TAG); + microservice.setType(BASE_MS_TYPE); + microservice.setLocation(LOCATION); + microservice.setNamespace(NAMESPACE); + microservice.setStatus(BaseMsStatus.ACTIVE); + microservice.setMetadata(prepareAuditFields()); + microservice.setMsInstances(createMsInstanceReferences()); + return microservice; + } + + private static List<Map<String, String>> createMsInstanceReferences() { + List<Map<String, String>> msInstanceRefs = new ArrayList<>(); + Map<String, String> msInstance_1 = new HashMap<>(); + msInstance_1.put("name", BASE_MS_NAME); + msInstance_1.put("id", "instance-1"); + Map<String, String> msInstance_2 = new HashMap<>(); + msInstance_2.put("name", BASE_MS_NAME); + msInstance_2.put("id", "instance-2"); + msInstanceRefs.add(msInstance_1); + msInstanceRefs.add(msInstance_2); + return msInstanceRefs; + } + + + public static AuditFields prepareAuditFields() { + return AuditFields.builder() + .createdBy(USER) // prepared by core + .createdOn(new Date(12323132L)) + .updatedBy(USER) + .updatedOn(new Date(12323133L)) + .notes(NOTE) + .labels(Arrays.asList(LABEL_1, LABEL_2)) + .build(); + + } + + public static MicroserviceUpdateRequest createUpdateMsRequest() { + MicroserviceUpdateRequest updateRequest = new MicroserviceUpdateRequest(); + updateRequest.setName("updatedName"); + updateRequest.setLocation(BaseMsLocation.EDGE); + updateRequest.setServiceName("updated-core-name"); + updateRequest.setNamespace("updatedNameSpace"); + updateRequest.setType(BaseMsType.ANALYTIC); + updateRequest.setUser("updater"); + + Map<String, Object> metadata = new HashMap(); + metadata.put("notes", "updatedNote"); + metadata.put("labels", Arrays.asList("updatedLabel1", "updatedLabel2")); + updateRequest.setMetadata(metadata); + return updateRequest; + } + + public static String asJsonString(final Object object) { + try { + return new ObjectMapper().writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/DeploymentArtifactObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/DeploymentArtifactObjectMother.java new file mode 100644 index 0000000..da52624 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/DeploymentArtifactObjectMother.java @@ -0,0 +1,222 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.objectmothers; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.MsInstanceInfo; + +import java.util.*; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.USER; + +public class DeploymentArtifactObjectMother { + + + public static final String BLUEPRINT_FILENAME = "hello-world-k8s-blueprint.yaml"; + public static final String BLUEPRINT_CONTENT = "\\n#Basic java app to print out at&t buzzwords\\n#1.0" + + ".0\\n#\\n---\\" + "ntosca_definitions_version: cloudify_dsl_1_3\\nimports:\\n- http://www.getcloudify" + + ".org/spec/cloudify/4.4/types" + ".yaml\\n- http://dockercentral.it.att" + + ".com:8093/nexus/repository/rawcentral/com.att.dcae.controller/type_files/" + "k8splugin/1.7.4/node-type" + + ".yaml\\n- http://dockercentral.it.att.com:8093/nexus/repository/rawcentral/com.att.d" + "cae.controller" + + "/type_files/relationship/2006001.1.0/types.yaml\\n- http://dockercentral.it.att.com:8093/nexus/" + + "repository/rawcentral/com.att.dcae.controller/type_files/cloudifydmaapplugin/1.4.10/node-type.yaml\\n- " + + "http:/" + "/dockercentral.it.att.com:8093/nexus/repository/rawcentral/com.att.dcae" + + ".controller/type_files/dcaepolicyplugi" + "n/2.3.3/node-type.yaml\\n- http://dockercentral.it.att" + + ".com:8093/nexus/repository/rawcentral/com.att.dcae.cont" + "roller/type_files/pgaas/0.3.2/pgaas_types" + + ".yaml\\ninputs:\\n ConsulTest1:\\n type: string\\n description" + ": test description\\n " + + "default: 'TEST1'\\n ConsulTest2:\\n type: string\\n description: test description\\n default: " + + "'TEST2'\\n aaf_cert_directory:\\n type: string\\n default: '/opt/app/aafcertman'\\n " + + "description: directory location for the aaf-tls certs\\n additionalsans:\\n type: string\\n " + + "default: ''\\n description: additional sans (string)\\n annotations:\\n default: {}\\n " + + "app_name:\\n type: string\\n default: 'dcae'\\n description: This is used to generateForRelease different" + + " secret code for DCAE or D2A based\\n on Tosca or Helm based BP\\n dcae_service_location:\\n " + + "type: string\\n description: Docker host override for docker bps (string)\\n " + + "dti_sidecar_cpu_limit:\\n type: string\\n default: '250m'\\n description: cpu limit for " + + "deployment (string)\\n dti_sidecar_cpu_request:\\n type: string\\n default: '250m'\\n " + + "description: cpu requested for deployment (string)\\n dti_sidecar_image:\\n type: string\\n " + + "default: 'dockercentral.it.att.com:5100/com.att.dcae.controller/dcae-controller-sidecar:19.11-001'\\n " + + " description: dti side car image for dti (string)\\n dti_sidecar_memory_limit:\\n type: string\\n " + + " default: '128Mi'\\n description: memory limit for deployment (string)\\n " + + "dti_sidecar_memory_request:\\n type: string\\n default: '128Mi'\\n description: memory " + + "requested for deployment (string)\\n dti_sidecar_port:\\n type: string\\n default: ''\\n " + + "description: Port for the side car (string)\\n hello-buzzword_cpu_limit:\\n type: string\\n " + + "default: '250m'\\n description: cpu limit for deployment (string)\\n hello-buzzword_cpu_request:\\n " + + " type: string\\n default: '250m'\\n description: cpu requested for deployment (string)\\n " + + "hello-buzzword_memory_limit:\\n type: string\\n default: '128Mi'\\n description: memory limit " + + "for deployment (string)\\n hello-buzzword_memory_request:\\n type: string\\n default: '128Mi'\\n " + + " description: memory requested for deployment (string)\\n idns_fqdn:\\n type: string\\n " + + "default: ''\\n description: The idns you will be using for your deployment (string)\\n image:\\n " + + "type: string\\n default: 'test-image-uri'\\n description: The docker image for your microservice " + + "(string)\\n namespace:\\n type: string\\n replicas:\\n type: integer\\n default: 1\\n " + + "description: The number of replicas for your kubernetes deployment (integer)\\n " + + "service_component_name_override:\\n type: string\\n default: 'hello-buzzword'\\n description: " + + "Unique identifier for your deployment (string)\\n use_aaf_tls:\\n type: boolean\\n default: " + + "false\\n description: To use or not use the aaf section (boolean)\\n use_dti_info:\\n type: " + + "boolean\\n default: true\\n description: Flag to use or not use dti (boolean)\\nnode_templates:\\n" + + " hello-buzzword_hello-buzzword:\\n type: dcae.nodes.ContainerizedServiceComponent\\n " + + "properties:\\n application_config:\\n services_calls: []\\n streams_publishes: {}\\n " + + " streams_subscribes: {}\\n ConsulTest1:\\n get_input: ConsulTest1\\n " + + "ConsulTest2:\\n get_input: ConsulTest2\\n docker_config:\\n healthcheck:\\n " + + " interval: 180s\\n timeout: 30s\\n script: \\\"true\\\"\\n type: docker\\n " + + " livehealthcheck:\\n interval: 180s\\n timeout: 30s\\n script: " + + "\\\"true\\\"\\n type: docker\\n reconfigs:\\n dti: dti/test-script\\n " + + "app_reconfig: /app-reconfig/test-script\\n env:\\n - name: DTI_DATA_DIR\\n value:" + + " /dtidata\\n - name: KUBE_CLUSTER_FQDN\\n value: {get_secret: " + + "kc-kubernetes_master_ip}\\n image:\\n get_input: image\\n location_id:\\n " + + "get_input: dcae_service_location\\n service_component_type: hello-buzzword\\n replicas:\\n " + + " get_input: replicas\\n service_component_name_override:\\n concat:\\n - " + + "get_secret: location_id\\n - '-'\\n - get_input: service_component_name_override\\n " + + "k8s_controller_type: statefulset\\n configuration:\\n file_content:\\n apiVersion: " + + "v1\\n clusters:\\n - name: default-cluster\\n cluster:\\n " + + "server:\\n concat:\\n - https://\\n - get_secret: " + + "kc-kubernetes_master_ip\\n - ':'\\n - get_secret: " + + "kc-kubernetes_master_port\\n insecure-skip-tls-verify: true\\n contexts:\\n " + + " - name: default-context\\n context:\\n cluster: default-cluster\\n " + + " namespace:\\n get_input: namespace\\n user: default-user\\n " + + "kind: Config\\n preferences: {}\\n users:\\n - name: default-user\\n " + + " user:\\n token:\\n get_secret:\\n concat:\\n " + + " - get_input: app_name\\n - -mechid-k8s-token\\n current-context: " + + "default-context\\n resource_config:\\n limits:\\n cpu:\\n get_input: " + + "hello-buzzword_cpu_limit\\n memory:\\n get_input: hello-buzzword_memory_limit\\n " + + " requests:\\n cpu:\\n get_input: hello-buzzword_cpu_request\\n " + + "memory:\\n get_input: hello-buzzword_memory_request\\n aaf_tls_info:\\n " + + "use_aaf_tls:\\n get_input: use_aaf_tls\\n cert_directory:\\n get_input: " + + "aaf_cert_directory\\n image: dockercentral.it.att.com:5100/com.att.ecompcntr" + + ".public/ecompc-aaf-init-container:1.0.2\\n env:\\n - name: NAMESPACE\\n " + + "valueFrom:\\n fieldRef:\\n fieldPath: metadata.namespace\\n - name: " + + "deployer_id\\n valueFrom:\\n secretKeyRef:\\n name:\\n " + + "concat:\\n - get_input: namespace\\n - -cert-secret\\n key: " + + "deployerid\\n - name: deployer_pass\\n valueFrom:\\n secretKeyRef:\\n " + + " name:\\n concat:\\n - get_input: namespace\\n - " + + "-cert-secret\\n key: deployerpass\\n - name: cert_id\\n valueFrom:\\n " + + " secretKeyRef:\\n name:\\n concat:\\n - get_input: " + + "namespace\\n - -cert-secret\\n key: certid\\n - name: cm_url\\n " + + " valueFrom:\\n secretKeyRef:\\n name:\\n concat:\\n " + + " - get_input: namespace\\n - -cert-secret\\n key: cmurl\\n - " + + "name: idns_fqdn\\n value:\\n get_input: idns_fqdn\\n - name: " + + "app_service_names\\n value:\\n concat:\\n - get_secret: location_id\\n " + + " - '-'\\n - get_input: service_component_name_override\\n args:\\n - " + + "place\\n - cmtemplate\\n - -idnsfqdn=$(idns_fqdn)\\n - -cmurl=$(cm_url)\\n -" + + " -deployerid=$(deployer_id)\\n - -deployerpass=$(deployer_pass)\\n - -certid=$(cert_id)\\n" + + " - -namespace=$(NAMESPACE)\\n - -services=$(app_service_names)\\n - concat:\\n " + + " - -additionalsans=\\n - get_input: additionalsans\\n use_aaf_tls_renewal: true\\n " + + " renewal_args:\\n - renew\\n - -idnsfqdn=$(idns_fqdn)\\n - -cmurl=$(cm_url)\\n" + + " resource_config:\\n limits:\\n cpu: 250m\\n memory: 256Mi\\n " + + " requests:\\n cpu: 100m\\n memory: 256Mi\\n annotations:\\n " + + "get_input: annotations\\n dti_info:\\n image:\\n get_input: dti_sidecar_image\\n " + + " use_dti_info:\\n get_input: use_dti_info\\n healthcheck:\\n interval: " + + "90s\\n timeout: 60s\\n type: https\\n endpoint: /healthcheck\\n " + + "livehealthcheck:\\n interval: 90s\\n timeout: 60s\\n type: https\\n " + + "endpoint: /healthcheck\\n dtidata_directory: /dtidata\\n resource_config:\\n " + + "limits:\\n cpu:\\n get_input: dti_sidecar_cpu_limit\\n memory:\\n " + + " get_input: dti_sidecar_memory_limit\\n requests:\\n cpu:\\n " + + "get_input: dti_sidecar_cpu_request\\n memory:\\n get_input: " + + "dti_sidecar_memory_request\\n env:\\n - name: DTI_DATA_DIR\\n value: /dtidata\\n " + + " - name: KUBE_CLUSTER_FQDN\\n value: {get_secret: kc-kubernetes_master_ip}\\n - " + + "name: KUBE_PROXY_FQDN\\n value: {get_secret: kube_proxy_fqdn}\\n - name: POD_SVC_PORT\\n" + + " value: '9999'\\n ports:\\n - concat:\\n - '9999:'\\n - " + + "get_input: dti_sidecar_port\\n relationships: []"; + + public static final String SPEC_FILE_AS_STRING = String.format("{\r\n\t\"self\": {\r\n\t\t\"component_type\": " + + "\"docker\",\r\n\t\t\"description\": \"Basic java app to print out at&t buzzwords\",\r\n\t\t\"name\": " + + "\"hello-buzzword\",\r\n\t\t\"version\": \"1.0.0\"\r\n\t},\r\n\t\r\n\t\"services\": {\r\n\t\t\"calls\": " + + "[],\r\n\t\t\"provides\": []\r\n\t},\r\n\t\"streams\": {\r\n\t\t\"publishes\": [],\r\n\t\t\"subscribes\":" + + " []\r\n\t},\r\n\t\"parameters\": [\r\n\t\t{\r\n \"name\": \"ConsulTest1\",\r\n " + + "\"value\": \"TEST1\",\r\n \"description\": \"Test consul output\"," + + "\r\n\t\t\t\"sourced_at_deployment\": true,\r\n\t\t\t\"designer_editable\": true," + + "\r\n\t\t\t\"policy_editable\": false,\r\n\t\t\t\"type\": \"string\" ,\r\n\t\t\t\"description\": \"test " + + "description\" \r\n },\r\n {\r\n \"name\": \"ConsulTest2\",\r\n " + + " \"value\": \"TEST2\",\r\n\t\t\t\"sourced_at_deployment\": true,\r\n\t\t\t\"designer_editable\": true," + + "\r\n\t\t\t\"policy_editable\": false,\r\n\t\t\t\"type\": \"string\",\r\n\t\t\t\"description\": \"test " + + "description\" \r\n }\r\n \r\n\t],\r\n\r\n\t\"auxilary\": {\r\n\t\t\"healthcheck\": " + + "{\r\n\t\t\t\"type\": \"docker\",\r\n \t\"script\": \"true\",\r\n \t\"timeout\": \"30s\"," + + "\r\n \t\"interval\": \"180s\"\r\n\t\t},\r\n\t\t\"livehealthcheck\": {\r\n\t\t\t\"type\": " + + "\"docker\",\r\n \t\"script\": \"true\",\r\n \t\"timeout\": \"30s\",\r\n " + + "\t\"interval\": \"180s\"\r\n\t\t},\r\n\t\t\"reconfigs\": {\r\n\t\t\t\"app_reconfig\" : " + + "\"/app-reconfig/test-script\",\r\n\t\t\t\"dti\" : \"dti/test-script\"}}," + + "\r\n\t\"artifacts\": [{\r\n\t\t\"type\": \"docker image\",\r\n\t\t\"uri\": " + + "\"test-image-uri\"\r\n\t}]\r\n}"); + + public static DeploymentArtifact createDeploymentArtifactDAO(DeploymentArtifactStatus status) { + DeploymentArtifact artifact = new DeploymentArtifact(); + artifact.setId("id-123"); + artifact.setFileName("helloworld-k8s-blueprint.yaml"); + artifact.setContent("some " + "yaml content"); + artifact.setStatus(status); + artifact.setVersion(1); + artifact.setMetadata(createMetaData()); + artifact.setMsInstanceInfo(createMsInstanceInfo()); + artifact.setSpecificationInfo(createSpecificationInfo()); + + return artifact; + } + + private static Map<String, Object> createSpecificationInfo() { + Map<String, Object> msInstanceInfo = new HashMap<>(); + msInstanceInfo.put("id", "id-123"); + return msInstanceInfo; + } + + private static MsInstanceInfo createMsInstanceInfo() { + MsInstanceInfo msInstanceInfo = new MsInstanceInfo(); + msInstanceInfo.setId(MsInstanceObjectMother.MS_INSTANCE_ID); + msInstanceInfo.setName(MsInstanceObjectMother.MS_INSTANCE_NAME); + msInstanceInfo.setRelease(MsInstanceObjectMother.RELEASE); + return msInstanceInfo; + } + + private static Map<String, Object> createMetaData() { + Map<String, Object> metadata = new HashMap<>(); + metadata.put("createdBy", USER); + metadata.put("createdOn", "someDate"); + metadata.put("notes", "This is a test Deployment Artifact"); + metadata.put("labels", Arrays.asList("hello", "world")); + return metadata; + } + + public static Map<String, Object> createBlueprintResponse() { + Map<String, Object> blueprintMap = new HashMap<>(); + blueprintMap.put("fileName", BLUEPRINT_FILENAME); + blueprintMap.put("content", BLUEPRINT_CONTENT); return blueprintMap; + } + + public static Map<String, Object> createToolboxBlueprintResponse() { + Map<String, Object> blueprintResponseMap = new HashMap<>(); + blueprintResponseMap.put("blueprint_name", "hello-buzzword-eom-k8s"); + blueprintResponseMap.put("blueprint_content", BLUEPRINT_CONTENT); + blueprintResponseMap.put("componentSpecValidated", true); + return blueprintResponseMap; + } + + public static List<DeploymentArtifact> createMockDeploymentArtifactsWithDifferentStatuses + (boolean devCompleteRequire) { + DeploymentArtifact d1; + if(devCompleteRequire){ + d1 = createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + }else { + d1 = createDeploymentArtifactDAO(DeploymentArtifactStatus.NOT_NEEDED); + } + DeploymentArtifact d2 = createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + return new ArrayList<>(Arrays.asList(d1, d2)); + } + +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/MsInstanceObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/MsInstanceObjectMother.java new file mode 100644 index 0000000..976e31c --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/MsInstanceObjectMother.java @@ -0,0 +1,112 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.objectmothers; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.DeploymentArtifactsRef; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstanceStatus; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceRequest; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +public class MsInstanceObjectMother { + + public static final String MS_INSTANCE_NAME = "ms-instance-1"; + public static final String MS_INSTANCE_ID = "id-123"; + public static final String RELEASE = "2002"; + public static final String VERSION = "1.1"; + public static final String USER = "user-1"; + public static final String BASE_MS_TAG = "ms-instance-1-tag"; + public static final String SCRUMLEAD = "Sam"; + public static final String SYSTEMSENGINEER = "John"; + + public static MsInstanceRequest getMsInstanceMockRequest() { + Map<String, Object> metadataFromRequest = buildMockMetadataForRequest(); + + MsInstanceRequest request = MsInstanceRequest.builder() + .name(MS_INSTANCE_NAME) + .release(RELEASE) + .version(VERSION) + .user(USER) + .metadata(metadataFromRequest) + .build(); + + return request; + } + + private static Map<String, Object> buildMockMetadataForRequest() { + Map<String, Object> metadataFromRequest = new HashMap<>(); + metadataFromRequest.put("pstDueDate", "14-04-2020"); + metadataFromRequest.put("pstDueIteration", "1.2"); + metadataFromRequest.put("eteDueDate", "21-05-2020"); + metadataFromRequest.put("eteDueIteration", "1.3"); + metadataFromRequest.put("scrumLead", SCRUMLEAD); + metadataFromRequest.put("systemsEngineer", SYSTEMSENGINEER); + return metadataFromRequest; + } + + + public static MsInstance createMsInstance() { + Map<String, Object> metadataFromResponse = buildMockMetadataForRequest().entrySet() + .stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + metadataFromResponse.put("createdOn", "currentDate"); + metadataFromResponse.put("createdBy", USER); + metadataFromResponse.put("scrumLead", SCRUMLEAD); + metadataFromResponse.put("systemsEngineer", SYSTEMSENGINEER); + + Map<String, Object> msInfo = new HashMap<>(); + msInfo.put("id", BaseMsObjectMother.BASE_MS_ID); + msInfo.put("name", BaseMsObjectMother.BASE_MS_NAME); + msInfo.put("tag", BASE_MS_TAG); + + MsInstance msInstance = MsInstance.builder() + .id(MS_INSTANCE_ID) + .name(MS_INSTANCE_NAME) + .release(RELEASE) + .version(VERSION) + .status(MsInstanceStatus.NEW) + .metadata(metadataFromResponse) + .msInfo(msInfo) + .activeSpec(SpecificationObjectMother.getMockSpecification(DeploymentType.DOCKER)) + .build(); + + return msInstance; + } + + public static MsInstance getMsInstanceWithExistingDeploymentArtifactRef() { + MsInstance msInstance = createMsInstance(); + + DeploymentArtifactsRef deploymentArtifactRef = new DeploymentArtifactsRef(); + deploymentArtifactRef.setMostRecentVersion(1); + + ArrayList<String> deploymentArtifactList = new ArrayList<>(); + deploymentArtifactList.add("id-456"); + deploymentArtifactRef.setDeploymentArtifacts(deploymentArtifactList); + + msInstance.setDeploymentArtifactsInfo(deploymentArtifactRef); + + return msInstance; + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/SpecificationObjectMother.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/SpecificationObjectMother.java new file mode 100644 index 0000000..3390998 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/objectmothers/SpecificationObjectMother.java @@ -0,0 +1,41 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.objectmothers; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.restapi.SpecificationRequest; +import org.onap.dcaegen2.platform.mod.model.specification.Specification; +import org.onap.dcaegen2.platform.mod.util.TestUtil; + +public class SpecificationObjectMother { + public static final String SPEC_REQUEST = "src/test/resources/http/requests/CreateSpecificationRequest.json"; + public static final String SPEC_RESPONSE = "src/test/resources/http/requests/CreateSpecificationResponse.json"; + + public static SpecificationRequest getSpecificationRequest() { + return TestUtil.deserializeJsonFileToModel(SPEC_REQUEST, SpecificationRequest.class); + } + + public static Specification getMockSpecification(DeploymentType type) { + Specification specification = TestUtil.deserializeJsonFileToModel(SPEC_RESPONSE, Specification.class); + specification.setType(type); + return specification; + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/persistence/DeploymentArtifactGatewayTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/persistence/DeploymentArtifactGatewayTest.java new file mode 100644 index 0000000..9bcd46c --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/persistence/DeploymentArtifactGatewayTest.java @@ -0,0 +1,147 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.persistence; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactFilter; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactSearch; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.mongo.deploymentartifact.DeploymentArtifactMongoGateway; +import org.onap.dcaegen2.platform.mod.mongo.deploymentartifact.DeploymentArtifactMongoRepo; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactGateway; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.MongoOperations; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.Arrays; +import java.util.List; + +@Disabled("Embedded mongodb jar is not available in the maven repo.") +@SpringBootTest +@ExtendWith(SpringExtension.class) +public class DeploymentArtifactGatewayTest { + + DeploymentArtifactGateway gateway; + + @Autowired + DeploymentArtifactMongoRepo repo; + + @Autowired + MongoOperations operations; + + @BeforeEach + public void setUp(){ + gateway = new DeploymentArtifactMongoGateway(repo); + + operations.dropCollection(DeploymentArtifact.class); + + String r_2008 = "2008"; + String r_2010 = "2010"; + + DeploymentArtifactStatus inDev = DeploymentArtifactStatus.IN_DEV; + DeploymentArtifactStatus devComplete = DeploymentArtifactStatus.DEV_COMPLETE; + + String tag_1 = "hello-one"; + String tag_2 = "hello-two"; + String tag_3 = "hello-three"; + + DeploymentArtifact artifact_1 = getDeploymentArtifact(r_2008, inDev, tag_1); + DeploymentArtifact artifact_2 = getDeploymentArtifact(r_2010, devComplete, tag_2); + DeploymentArtifact artifact_3 = getDeploymentArtifact(r_2008, devComplete, tag_3); + + operations.insertAll(Arrays.asList(artifact_1, artifact_2, artifact_3)); + operations.findAll(DeploymentArtifact.class).forEach(System.out::println); + + System.out.println(); + } + + private static DeploymentArtifact getDeploymentArtifact(String r_2008, DeploymentArtifactStatus inDev, + String tag) { + DeploymentArtifact artifact_1 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(inDev); + artifact_1.getMsInstanceInfo().setRelease(r_2008); + //Currently searching tag in filename as it is not present in DeploymentArtifact record + artifact_1.setFileName(tag); + artifact_1.setId(null); + + return artifact_1; + } + + @Test + public void findByOnlyRelease() throws Exception { + DeploymentArtifactSearch search = new DeploymentArtifactSearch(); + DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); + filter.setRelease("2008"); + search.setFilter(filter); + + List<DeploymentArtifact> artifacts = gateway.findAll(search); + Assertions.assertThat(artifacts.size()).isEqualTo(2); + } + + @Test + public void findWithOnlyStatus() throws Exception { + DeploymentArtifactSearch search = new DeploymentArtifactSearch(); + DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); + filter.setStatus(DeploymentArtifactStatus.IN_DEV); + search.setFilter(filter); + + List<DeploymentArtifact> artifacts = gateway.findAll(search); + + Assertions.assertThat(artifacts.size()).isEqualTo(1); + } + + @Test + public void findWithStatusAndRelease() throws Exception { + DeploymentArtifactSearch search = new DeploymentArtifactSearch(); + DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); + filter.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); + filter.setRelease("2008"); + search.setFilter(filter); + + List<DeploymentArtifact> artifacts = gateway.findAll(search); + + Assertions.assertThat(artifacts.size()).isEqualTo(3); + } + + @Test + public void findWithTag() throws Exception { + DeploymentArtifactSearch search = new DeploymentArtifactSearch(); + DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); + filter.setTag("hello-one"); + search.setFilter(filter); + + List<DeploymentArtifact> artifacts = gateway.findAll(search); + + Assertions.assertThat(artifacts.size()).isEqualTo(1); + } + + @Test + public void findWithNoQuery() throws Exception { + List<DeploymentArtifact> artifacts = gateway.findAll(new DeploymentArtifactSearch()); + Assertions.assertThat(artifacts.size()).isEqualTo(0); + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/util/TestUtil.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/util/TestUtil.java new file mode 100644 index 0000000..f9a45da --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/util/TestUtil.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.util; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.File; +import java.io.IOException; +import java.util.Map; + +public class TestUtil { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private TestUtil() {} + + public static Map<String, Object> readJsonFileAsObjectMap(String filePath) { + try { + return MAPPER.readValue(new File(filePath), new TypeReference<Map<String, Object>>() {}); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(); + } + } + + public static <T> T deserializeJsonFileToModel(String filePath, Class<T> modelClass) { + try { + return MAPPER.readValue(new File(filePath), modelClass); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(); + } + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java new file mode 100644 index 0000000..c89b4dc --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java @@ -0,0 +1,165 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.exceptions.OperationNotAllowedException; +import org.onap.dcaegen2.platform.mod.model.exceptions.ResourceConflictException; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.BaseMicroserviceController; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsService; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.Arrays; + +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_NAME_CONFLICT_MESSAGE; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(BaseMicroserviceController.class) +class BaseMicroserviceControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private MsService mockBaseMsService; + + @BeforeEach + void setUp() { + } + + @Test + void test_GetAllBaseMicroservices_returnsListOfDTOs() throws Exception { + //arrange + BaseMicroservice ms1 = new BaseMicroservice(); + ms1.setName("HelloWorld1"); + BaseMicroservice ms2 = new BaseMicroservice(); + ms2.setName("HelloWorld2"); + + Mockito.when(mockBaseMsService.getAllMicroservices()).thenReturn(Arrays.asList(ms1, ms2)); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.get("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))); + } + + @Test + void test_addBaseMicroservice_returnsMicroservice() throws Exception { + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + + //response + BaseMicroservice microserviceDao = BaseMsObjectMother.createMockMsObject(); + + Mockito.when(mockBaseMsService.createMicroservice(microserviceRequest)).thenReturn(microserviceDao); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect((MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(BaseMsObjectMother.BASE_MS_ID)))) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo(BaseMsObjectMother.BASE_MS_NAME))) + .andExpect(MockMvcResultMatchers.jsonPath("$.metadata.createdBy", Matchers.equalTo(BaseMsObjectMother.USER))); + } + + @Test + void test_addBaseMicroserviceWithDuplicateName_shouldThrowConflictError() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + Mockito.when(mockBaseMsService.createMicroservice(ArgumentMatchers.any())).thenThrow(new ResourceConflictException(MICROSERVICE_NAME_CONFLICT_MESSAGE)); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest))) + .andExpect(MockMvcResultMatchers.status().isConflict()); + } + + @Test + void test_updateBaseMicroserviceEndpoint() throws Exception{ + MicroserviceUpdateRequest microserviceRequest = BaseMsObjectMother.createUpdateMsRequest(); + String requestedMsId = "id-123"; + + mockMvc.perform(MockMvcRequestBuilders.patch(String.format(BaseMicroserviceController.API_BASE_MICROSERVICE + "/%s", requestedMsId)) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isNoContent()); + Mockito.verify(mockBaseMsService, Mockito.times(1)).updateMicroservice(requestedMsId, microserviceRequest); + } + + @Test + void test_OperationNotAllowedExceptionThrows409() throws Exception{ + MicroserviceUpdateRequest microserviceRequest = BaseMsObjectMother.createUpdateMsRequest(); + String requestedMsId = "id-123"; + Mockito.doThrow(new OperationNotAllowedException("")). + when(mockBaseMsService).updateMicroservice(requestedMsId, microserviceRequest); + + mockMvc.perform(MockMvcRequestBuilders.patch(String.format(BaseMicroserviceController.API_BASE_MICROSERVICE + "/%s", requestedMsId)) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest))) + .andExpect(MockMvcResultMatchers.status().isConflict()); + } + + @Test + void test_validateMsRequestShouldThrowCorrectResponse() throws Exception { + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + microserviceRequest.setName(" "); + microserviceRequest.setTag("123"); + microserviceRequest.setServiceName("123"); + microserviceRequest.setUser(" "); + + //response + BaseMicroservice microserviceDao = BaseMsObjectMother.createMockMsObject(); + + Mockito.when(mockBaseMsService.createMicroservice(microserviceRequest)).thenReturn(microserviceDao); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message", Matchers.equalTo("Validation failed."))) + .andExpect(MockMvcResultMatchers.jsonPath("$.errors", Matchers.hasSize(4))) + ; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java new file mode 100644 index 0000000..c8942b1 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java @@ -0,0 +1,170 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.BlueprintFileNameCreateException; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.DeploymentArtifactNotFound; +import org.onap.dcaegen2.platform.mod.model.restapi.DeploymentArtifactPatchRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.DeploymentArtifactController; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.Arrays; +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +@WebMvcTest(DeploymentArtifactController.class) +class DeploymentArtifactControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + DeploymentArtifactService service; + + @BeforeEach + void setUp() { + } + + @Test + void test_GenerateDeploymentArtifactEndpoint_returnsBlueprint() throws Exception{ + String url = String.format("/api/deployment-artifact/%s?user=%s", MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER); + DeploymentArtifact response = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + Mockito.when(service.generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER)).thenReturn(response); + + mockMvc.perform(post(url)) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.jsonPath("$.fileName").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.content").exists()); + + Mockito.verify(service, Mockito.times(1)).generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER); + } + + @Test + void test_RaiseExceptionIfBlueprintNameCanNotBeCreated() throws Exception{ + String url = String.format("/api/deployment-artifact/%s?user=%s", MsInstanceObjectMother.MS_INSTANCE_ID, + MsInstanceObjectMother.USER); + DeploymentArtifact response = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + Mockito.when(service.generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER)).thenThrow(new BlueprintFileNameCreateException("")); + + mockMvc.perform(post(url)) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + } + + @Test + void test_GetAllDeploymentArtifactsShouldReturnList() throws Exception{ + List<DeploymentArtifact> daos = createDaos(); + Mockito.when(service.getAllDeploymentArtifacts()).thenReturn(daos); + + mockMvc.perform(get("/api/deployment-artifact")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))); + + } + + private List<DeploymentArtifact> createDaos() { + DeploymentArtifact dao1 = new DeploymentArtifact(); + dao1.setId("123"); + DeploymentArtifact dao2 = new DeploymentArtifact(); + dao2.setId("456"); + + return Arrays.asList(dao1, dao2); + } + + @Test + void test_GetAllDeploymentArtifactTestShouldReturnAList() throws Exception{ + + mockMvc.perform(get(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + DeploymentArtifactController.GET_STATUSES)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(DeploymentArtifactStatus.values().length))); + } + + @Test + void test_ifUserIsNullRaiseException() throws Exception{ + String id = "id-123"; + String user = ""; + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + id + "?user=" + user) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(new DeploymentArtifactPatchRequest()))) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); + } + + @Test + void test_ChangeStatusOfDeploymentArtifact() throws Exception{ + + String id = "id-123"; + String user = "user1"; + DeploymentArtifactPatchRequest partialDto = new DeploymentArtifactPatchRequest(); + partialDto.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + id + "?user=" + user) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(partialDto))) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").exists()); + + Mockito.verify(service, Mockito.times(1)).updateDeploymentArtifact(id, partialDto, user); + + } + + @Test + void test_deploymentArtifactIdNotFound() throws Exception{ + String wrongId = "wrong-id"; + DeploymentArtifactPatchRequest partialDto = new DeploymentArtifactPatchRequest(); + partialDto.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); + + Mockito.doThrow(new DeploymentArtifactNotFound("")).when(service). + updateDeploymentArtifact(wrongId, partialDto, "user-1"); + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + wrongId + "?user=" + "user-1") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(partialDto))) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); + } + + @Test + void test_deleteDeploymentArtifactEndpoint() throws Exception{ + String deploymentArtifactId = "id-123"; + String user = "user-1"; + mockMvc.perform(delete(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + deploymentArtifactId + "?user=" + user)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").exists()); + Mockito.verify(service, Mockito.times(1)).deleteDeploymentArtifact(deploymentArtifactId); + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java new file mode 100644 index 0000000..852fb10 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java @@ -0,0 +1,145 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.MicroserviceInstanceController; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(MicroserviceInstanceController.class) +class MicroserviceInstanceControllerTest { + + @MockBean + MsInstanceService service; + + @Autowired + MockMvc mockMvc; + + @BeforeEach + void setUp() { + } + + @Test + void getAll() throws Exception { + MsInstance instance_1 = MsInstance.builder().id("123").build(); + MsInstance instance_2 = MsInstance.builder().id("345").build(); + + when(service.getAll()).thenReturn(Arrays.asList(instance_1,instance_2)); + + mockMvc.perform(get("/api/microservice-instance") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$",hasSize(2))); + verify(service, times(1)).getAll(); + } + + @Test + void createMsInstance_shouldReturn201AndResponseBody() throws Exception { + + MsInstanceRequest request = getMsInstanceMockRequest(); + MsInstance msInstance = createMsInstance(); + + when(service.createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME, request)).thenReturn(msInstance); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/microservice-instance/"+ BaseMsObjectMother.BASE_MS_NAME) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(request)).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name",equalTo(MS_INSTANCE_NAME))); + + verify(service, times(1)).createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME,request); + } + + @Test + void patchMsInstance_shouldReturn204NoContent() throws Exception{ + //given + String updatedVersion = "updatedVersion"; + String updatedRelease = "updatedRelease"; + + MsInstance mockedMsInstance = prepareMockMsInstance(updatedVersion, updatedRelease); + String msInstanceId = mockedMsInstance.getId(); + + MsInstanceUpdateRequest updateRequest = prepareMsInstanceUpdateRequest(updatedVersion, updatedRelease); + + when(service.updateMsInstance(updateRequest, msInstanceId)).thenReturn(mockedMsInstance); + + mockMvc.perform(patch("/api/microservice-instance/" + msInstanceId) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(updateRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.release", equalTo(updatedRelease))) + .andExpect(jsonPath("$.version", equalTo(updatedVersion))) + .andExpect(jsonPath("$.metadata.scrumLead", equalTo("updatedScrumLead"))); + + verify(service, times(1)).updateMsInstance(updateRequest, msInstanceId); + } + + private MsInstanceUpdateRequest prepareMsInstanceUpdateRequest(String updatedVersion, String updatedRelease) { + MsInstanceUpdateRequest updateRequest = new MsInstanceUpdateRequest(); + updateRequest.setRelease(updatedRelease); + updateRequest.setVersion(updatedVersion); + updateRequest.setMetadata(prepareMetadataToBeUpdated()); + return updateRequest; + } + + private Map<String, Object> prepareMetadataToBeUpdated() { + Map<String, Object> metadata = new HashMap<>(); + metadata.put("scrumLead", "updatedScrumLead"); + return metadata; + } + + private MsInstance prepareMockMsInstance(String updatedVersion, String updatedRelease) { + MsInstance msInstanceToBeUpdated = MsInstanceObjectMother.createMsInstance(); + msInstanceToBeUpdated.setVersion(updatedVersion); + msInstanceToBeUpdated.setRelease(updatedRelease); + msInstanceToBeUpdated.getMetadata().put("scrumLead", "updatedScrumLead"); + return msInstanceToBeUpdated; + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java new file mode 100644 index 0000000..d71f8dd --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import java.util.Set; + +public class MsRequestValidationTest { + + public Validator validator; + private MicroserviceCreateRequest request; + + @BeforeEach + public void setup(){ + validator = Validation.buildDefaultValidatorFactory().getValidator(); + request = BaseMsObjectMother.createMockMsRequest(); + } + + @Test + void test_msNameShouldNotBeBlank(){ + request.setName(" "); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msTagShouldNotBeNull(){ + request.setTag(null); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + + } + + @Test + void test_msTagShouldFollowRegex() throws Exception{ + request.setTag("ms-1"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msTagSizeValidation() throws Exception { + request.setTag("core-name-should-not-exceed-fifty-chars-core-name-should-not-exceed-fifty-chars"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msServiceNameShouldFollowRegex() throws Exception{ + request.setServiceName("ms-1"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_userShouldNotBeBlank(){ + request.setUser(" "); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java new file mode 100644 index 0000000..64f9c00 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.restapi.SpecificationRequest; +import org.onap.dcaegen2.platform.mod.model.specification.Specification; +import org.onap.dcaegen2.platform.mod.web.controller.SpecificationController; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.asJsonString; +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.MS_INSTANCE_ID; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getMockSpecification; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getSpecificationRequest; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(SpecificationController.class) +public class SpecificationControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + private SpecificationService mockSpecificationService; + + @BeforeEach + void setup() { + } + + @Test + void test_addSpecification_returnsSpecification() throws Exception { + //arrange + SpecificationRequest specificationRequest = getSpecificationRequest(); + Specification specification = getMockSpecification(DeploymentType.DOCKER); + + when(mockSpecificationService.createSpecification(MS_INSTANCE_ID, specificationRequest)).thenReturn(specification); + + //act/assert + mockMvc.perform(post("/api/specification/" + MS_INSTANCE_ID) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(specificationRequest)).accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(status().isCreated()); + verify(mockSpecificationService, times(1)).createSpecification(MS_INSTANCE_ID, specificationRequest); + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java new file mode 100644 index 0000000..1d84b60 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java @@ -0,0 +1,209 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.MsInstanceInfo; +import org.onap.dcaegen2.platform.mod.model.exceptions.msinstance.MsInstanceNotFoundException; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsService; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceGateway; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceStatusChangeHandler; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsInstanceServiceImplTest { + + @Spy + private MsInstanceServiceImpl service = new MsInstanceServiceImpl(); + + @Mock + private MsInstanceGateway msInstanceRepository; + + @Mock + private MsService msService; + + @Mock + private SpecificationService specificationService; + + @Mock + private DeploymentArtifactService deploymentArtifactService; + + @Mock + private MsInstanceStatusChangeHandler msInstanceStatusChangeHandler; + + + @BeforeEach + void setUp() { + service.setMsService(msService); + service.setSpecificationService(specificationService); + service.setDeploymentArtifactService(deploymentArtifactService); + service.setMsInstanceRepository(msInstanceRepository); + service.setMsInstanceStatusChangeHandler(msInstanceStatusChangeHandler); + } + + @Test + void getAll() { + MsInstance instance_1 = MsInstance.builder().id("123").build(); + MsInstance instance_2 = MsInstance.builder().id("345").build(); + + when(msInstanceRepository.findAll()).thenReturn(Arrays.asList(instance_1, instance_2)); + + List<MsInstance> instances = service.getAll(); + + assertThat(instances.size()).isEqualTo(2); + verify(msInstanceRepository, times(1)).findAll(); + } + + @Test + void test_getMsInstanceById() throws Exception{ + MsInstance expected = MsInstanceObjectMother.createMsInstance(); + + when(msInstanceRepository.findById(MS_INSTANCE_ID)).thenReturn(Optional.of(expected)); + + MsInstance original = service.getMsInstanceById(MS_INSTANCE_ID); + + assertThat(original.getId()).isEqualTo(expected.getId()); + } + + @Test + void test_msIntanceNotFound_willRaiseException() throws Exception{ + when(msInstanceRepository.findById(MS_INSTANCE_ID)).thenReturn(Optional.empty()); + assertThatExceptionOfType(MsInstanceNotFoundException.class).isThrownBy( + () -> service.getMsInstanceById(MS_INSTANCE_ID)); + } + + //TODO require cleaning and more assertions + @Test + void createMicroserviceInstance() { + + BaseMicroservice microservice = BaseMsObjectMother.createMockMsObject(); + MsInstanceRequest request = getMsInstanceMockRequest(); + MsInstance msInstanceMockDao = createMsInstance(); + + when(msService.getMicroserviceByName(BaseMsObjectMother.BASE_MS_NAME)).thenReturn(microservice); + when(msInstanceRepository.findByNameAndRelease(request.getName(), request.getRelease())) + .thenReturn(Optional.empty()); + when(msInstanceRepository.save(any())).thenReturn(msInstanceMockDao); + + MsInstance msInstance = service.createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME,request); + + assertThat(msInstance.getId()).isEqualTo(msInstance.getId()); + assertThat(msInstance.getName()).isEqualTo(msInstance.getName()); + assertThat(msInstance.getMsInfo().keySet()).isEqualTo(msInstanceMockDao.getMsInfo().keySet()); + + verify(msService, times(1)).getMicroserviceByName(BaseMsObjectMother.BASE_MS_NAME); + verify(msInstanceRepository, times(1)).save(any(MsInstance.class)); + verify(msService, times(1)). + saveMsInstanceReferenceToMs(microservice, msInstance); + + } + + @Test + void test_updateMsInstance() { + + } + + @Test + void updateStatusBasedOnDeploymentArtifactsStatuses() { + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceRepository.findById(msInstance.getId())).thenReturn(Optional.of(msInstance)); + + service.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance.getId()); + + verify(msInstanceStatusChangeHandler, times(1)).updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + verify(service, times(1)).updateMsInstance(msInstance); + + } + + @Test + void test_removeDeploymentArtifactFromMsInstance() { + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + DeploymentArtifact deploymentArtifact = createDeploymentArtifact(msInstance); + + when(msInstanceRepository.findById(msInstance.getId())).thenReturn(Optional.of(msInstance)); + //when(msInstanceStatusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(any())).thenReturn(msInstance); + + service.removeDeploymentArtifactFromMsInstance(deploymentArtifact); + + assertThat(msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts().contains(deploymentArtifact.getId())).isFalse(); + verify(msInstanceStatusChangeHandler, times(1)).updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + verify(service, times(1)).updateMsInstance(msInstance); + + } + + @Test + void updateMicroserviceReference() throws Exception{ + BaseMicroservice microservice = BaseMsObjectMother.createMockMsObject(); + MsInstance msInstance_1 = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + msInstance_1.setId("instance-1"); + msInstance_1.getMsInfo().put("name", "old-ms"); + MsInstance msInstance_2 = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + msInstance_2.setId("instance-2"); + msInstance_2.getMsInfo().put("name", "old-ms"); + + when(msInstanceRepository.findById("instance-1")).thenReturn(Optional.of(msInstance_1)); + when(msInstanceRepository.findById("instance-2")).thenReturn(Optional.of(msInstance_2)); + + service.updateMicroserviceReference(microservice); + + assertThat(msInstance_1.getName()).isEqualTo(microservice.getName()); + assertThat(msInstance_2.getName()).isEqualTo(microservice.getName()); + + assertThat(msInstance_1.getMsInfo().get("name")).isEqualTo(microservice.getName()); + assertThat(msInstance_2.getMsInfo().get("name")).isEqualTo(microservice.getName()); + + verify(service, times(2)).getMsInstanceById(anyString()); + verify(msInstanceRepository, times(2)).save(any(MsInstance.class)); + } + + private DeploymentArtifact createDeploymentArtifact(MsInstance msInstance) { + DeploymentArtifact deploymentArtifact = new DeploymentArtifact(); + deploymentArtifact.setId(msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts().get(0)); + + MsInstanceInfo msInstanceInfo = new MsInstanceInfo(); + msInstanceInfo.setId(msInstance.getId()); + deploymentArtifact.setMsInstanceInfo(msInstanceInfo); + return deploymentArtifact; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java new file mode 100644 index 0000000..9339b26 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java @@ -0,0 +1,92 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstanceStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceStatusChangeHandler; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsInstanceStatusChangeHandlerTest { + + MsInstanceStatusChangeHandler statusChangeHandler; + + @Mock + MsInstanceService msInstanceService; + + @Mock + DeploymentArtifactService deploymentArtifactService; + + @BeforeEach + void setup() throws Exception{ + statusChangeHandler = new MsInstanceStatusChangeHandler(); + statusChangeHandler.setMsInstanceService(msInstanceService); + statusChangeHandler.setDeploymentArtifactService(deploymentArtifactService); + } + + @Test + void handleStatusChangeFromDeploymentArtifactsWithDevComplete() { + //arrange + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + + when(deploymentArtifactService.findByMsInstanceId(msInstance.getId())).thenReturn( + DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true) + ); + + //act + statusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + + //assert + assertThat(msInstance.getStatus()).isEqualTo(MsInstanceStatus.DEV_COMPLETE); + verify(deploymentArtifactService, times(1)).findByMsInstanceId(msInstance.getId()); + } + + @Test + void handleStatusChangeFromDeploymentArtifactsWithoutDevComplete() { + //arrange + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + + //when(msInstanceService.getMsInstanceById(msInstance.getId())).thenReturn(msInstance); + when(deploymentArtifactService.findByMsInstanceId(msInstance.getId())).thenReturn( + DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(false) + ); + + //act + statusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + + //assert + assertThat(msInstance.getStatus()).isEqualTo(MsInstanceStatus.IN_DEV); + verify(deploymentArtifactService, times(1)).findByMsInstanceId(msInstance.getId()); + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java new file mode 100644 index 0000000..8604f1a --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java @@ -0,0 +1,217 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsLocation; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsType; +import org.onap.dcaegen2.platform.mod.model.exceptions.ResourceConflictException; +import org.onap.dcaegen2.platform.mod.model.exceptions.basemicroservice.BaseMicroserviceNotFoundException; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.BaseMicroserviceGateway; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.*; + +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_NAME_CONFLICT_MESSAGE; +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_TAG_CONFLICT_MESSAGE; +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.createMockMsObject; +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.createMockMsRequest; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsServiceImplTest { + + @Mock + private BaseMicroserviceGateway repository; + + @Mock + private MsInstanceService msInstanceService; + + @Spy + private MsServiceImpl baseMsService = new MsServiceImpl(); + + @BeforeEach + void setup() throws Exception{ + baseMsService.setRepository(repository); + baseMsService.setMsInstanceService(msInstanceService); + } + + /**GET MICROSERVICE TESTS*/ + @Test + void getAll() { + //arrange + BaseMicroservice ms1 = new BaseMicroservice(); + ms1.setName("HelloWorld1"); + BaseMicroservice ms2 = new BaseMicroservice(); + ms2.setName("HelloWorld2"); + + when(repository.findAll()).thenReturn(Arrays.asList(ms1, ms2)); + + //act + List<BaseMicroservice> microservices = baseMsService.getAllMicroservices(); + + //assert + assertThat(microservices).hasSizeGreaterThan(0); + } + + @Test + void test_getMicroserviceById() throws Exception{ + BaseMicroservice expectedMicroservice = BaseMsObjectMother.createMockMsObject(); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.of(expectedMicroservice)); + + BaseMicroservice resultMicroservice = baseMsService.getMicroserviceById(baseMsId); + + assertThat(resultMicroservice).isEqualTo(expectedMicroservice); + verify(repository, times(1)).findById(baseMsId); + } + + @Test + void test_ifMicroserviceNotFoundRaiseException() throws Exception{ + BaseMicroservice expectedMicroservice = BaseMsObjectMother.createMockMsObject(); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.empty()); + + assertThatExceptionOfType(BaseMicroserviceNotFoundException.class).isThrownBy( + () -> baseMsService.getMicroserviceById(baseMsId) + ); + } + + /**CREATE MICROSERVICE TESTS*/ + @Test + void createMicroservice() { + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice expected = createMockMsObject(); + + when(repository.save(any())).thenReturn(expected); + + //act + BaseMicroservice actual = baseMsService.createMicroservice(microserviceRequest); + + //assert + assertThat(actual.getMetadata().getCreatedBy()).isEqualTo(microserviceRequest.getUser()); + assertThat(actual.getMetadata().getUpdatedBy()).isEqualTo(microserviceRequest.getUser()); + } + + @Test + void AddingMsWithDuplicateName_shouldThrowException() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice existedMicroservice = createMockMsObject(); + + when(repository.findByName(any())).thenReturn(Optional.of(existedMicroservice)); + + //act/assert + assertThatThrownBy(() -> baseMsService.createMicroservice((microserviceRequest))) + .isInstanceOf(ResourceConflictException.class) + .hasMessage(MICROSERVICE_NAME_CONFLICT_MESSAGE); + } + @Test + void AddingMsWithDuplicateTag_shouldThrowException() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice existedMicroservice = createMockMsObject(); + + when(repository.findByTag(any())).thenReturn(Optional.of(existedMicroservice)); + + //act/assert + assertThatThrownBy(() -> baseMsService.createMicroservice((microserviceRequest))) + .isInstanceOf(ResourceConflictException.class) + .hasMessage(MICROSERVICE_TAG_CONFLICT_MESSAGE); + } + + /**UPDATE MICROSERVICE TESTS*/ + @Test + void test_updateMicroservice() throws Exception{ + MicroserviceUpdateRequest updateRequest = createUpdateMsRequest(); + + BaseMicroservice msToBeUpdated = BaseMsObjectMother.createMockMsObject(); + Date updateTimeBefore = new Date(msToBeUpdated.getMetadata().getUpdatedOn().getTime()); + + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.of(msToBeUpdated)); + + baseMsService.updateMicroservice(baseMsId, updateRequest); + + //assert + assertUpdatedMsFileds(updateRequest, msToBeUpdated, updateTimeBefore); + verify(baseMsService, times(1)).getMicroserviceById(baseMsId); + verify(msInstanceService, times(1)).updateMicroserviceReference(msToBeUpdated); + verify(repository, times(1)).save(msToBeUpdated); + } + +/* @Test + void test_msTagChangeShouldNotBeAllowed() throws Exception{ + MicroserviceCreateRequest updateRequest = new MicroserviceCreateRequest(); + updateRequest.setTag("updateTag"); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + assertThatExceptionOfType(OperationNotAllowedException.class).isThrownBy( + () -> baseMsService.updateMicroservice(baseMsId, updateRequest) + ); + }*/ + + private void assertUpdatedMsFileds(MicroserviceUpdateRequest updateRequest, BaseMicroservice msToBeUpdated, + Date updateTimeBefore) { + assertThat(msToBeUpdated.getName()).isEqualTo(updateRequest.getName()); + assertThat(msToBeUpdated.getLocation()).isEqualTo(updateRequest.getLocation()); + assertThat(msToBeUpdated.getServiceName()).isEqualTo(updateRequest.getServiceName()); + assertThat(msToBeUpdated.getNamespace()).isEqualTo(updateRequest.getNamespace()); + assertThat(msToBeUpdated.getType()).isEqualTo(updateRequest.getType()); + + assertThat(msToBeUpdated.getMetadata().getUpdatedBy()).isEqualTo(updateRequest.getUser()); + assertThat(msToBeUpdated.getMetadata().getUpdatedOn()).isNotEqualTo(updateTimeBefore); + + assertThat(msToBeUpdated.getMetadata().getNotes()).isEqualTo(updateRequest.getMetadata().get("notes")); + assertThat(msToBeUpdated.getMetadata().getLabels()).isEqualTo(updateRequest.getMetadata().get("labels")); + } + + private MicroserviceUpdateRequest createUpdateMsRequest() { + MicroserviceUpdateRequest updateRequest = new MicroserviceUpdateRequest(); + updateRequest.setName("updatedName"); + updateRequest.setLocation(BaseMsLocation.EDGE); + updateRequest.setServiceName("updatedServiceName"); + updateRequest.setNamespace("updatedNameSpace"); + updateRequest.setType(BaseMsType.ANALYTIC); + updateRequest.setUser("updater"); + + Map<String, Object> metadata = new HashMap(); + metadata.put("notes", "updatedNote"); + metadata.put("labels", Arrays.asList("updatedLabel1", "updatedLabel2")); + updateRequest.setMetadata(metadata); + return updateRequest; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java new file mode 100644 index 0000000..dff0727 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java @@ -0,0 +1,103 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.SpecificationRequest; +import org.onap.dcaegen2.platform.mod.model.specification.Specification; +import org.onap.dcaegen2.platform.mod.model.specification.SpecificationStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationGateway; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationValidatorService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.MS_INSTANCE_ID; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getMockSpecification; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getSpecificationRequest; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith({MockitoExtension.class}) +public class SpecificationServiceTest { + + private SpecificationServiceImpl service; + + @Mock + private SpecificationGateway specRepo; + + @Mock + private MsInstanceService msInstanceService; + + @Mock + private SpecificationValidatorService validatorService; + + @BeforeEach + void setUp() { + service = new SpecificationServiceImpl(); + service.setMsInstanceService(msInstanceService); + service.setSpecificationValidatorService(validatorService); + service.setSpecificationGateway(specRepo); + } + + @Test + void createSpecificationTest() throws Exception { + //given + SpecificationRequest request = getSpecificationRequest(); + Specification specFromRepo = getMockSpecification(DeploymentType.K8S); + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + when(specRepo.save(any(Specification.class))).thenReturn(specFromRepo); + + //when + Specification spec = service.createSpecification(MS_INSTANCE_ID, request); + + //then + assertThatFieldsAreCorrect(request, spec); + verifyCalls(request, msInstance); + + } + + private void assertThatFieldsAreCorrect(SpecificationRequest request, Specification spec) { + assertThat(spec.getStatus()).isEqualTo(SpecificationStatus.ACTIVE); + assertThat(spec.getSpecContent()).isEqualTo(request.getSpecContent()); + assertThat(spec.getPolicyJson()).isEqualTo(request.getPolicyJson()); + assertThat(spec.getType()).isEqualTo(request.getType()); + assertThat(spec.getMetadata().get("createdBy")).isEqualTo(request.getUser()); + assertThat(spec.getMetadata().get("createdOn")).isNotNull(); + assertThat(spec.getMsInstanceInfo()).isNotNull(); + } + + private void verifyCalls(SpecificationRequest request, MsInstance msInstance) { + verify(msInstanceService, times(1)).getMsInstanceById(MS_INSTANCE_ID); + verify(validatorService, times(1)).validateSpecForRelease(request, msInstance.getRelease()); + verify(specRepo, times(2)).save(any(Specification.class)); + verify(msInstanceService, times(1)).updateMsInstance(msInstance); + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java new file mode 100644 index 0000000..12a7dd2 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java @@ -0,0 +1,89 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.BlueprintFileNameCreateException; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +class ArtifactFileNameCreatorTest { + + private ArtifactFileNameCreator fileNameCreator; + + @BeforeEach + void setUp() { + fileNameCreator = new ArtifactFileNameCreator(); + } + + @Test + void test_createCorrectBlueprintFileName() throws Exception{ + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + String expectedName = createExpectedName(msInstance); + + //act + String fileName = fileNameCreator.createFileName(msInstance, 1); + + //assert + Assertions.assertThat(fileName).isEqualTo(expectedName); + } + + @Test + void test_missingTagForFileNameCreation_ShouldRaiseException() throws Exception{ + + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + msInstance.setMsInfo(new HashMap<>()); + + Assertions.assertThatExceptionOfType(BlueprintFileNameCreateException.class).isThrownBy( + () -> fileNameCreator.createFileName(msInstance, 1) + ); + } + + @Test + void test_missingSpecForFileNameCreation_ShouldRaiseException() throws Exception{ + + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + msInstance.setActiveSpec(null); + + Assertions.assertThatExceptionOfType(BlueprintFileNameCreateException.class).isThrownBy( + () -> fileNameCreator.createFileName(msInstance, 1) + ); + } + + + private String createExpectedName(MsInstance msInstance) { + String fileName = MsInstanceObjectMother.BASE_MS_TAG + "_" + + DeploymentType.DOCKER.toString().toLowerCase() + "_" + + msInstance.getRelease() + "_" + + "1" + + ".yaml"; + + return fileName; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java new file mode 100644 index 0000000..749d8b1 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java @@ -0,0 +1,250 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.DeploymentArtifactNotFound; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.DeploymentArtifactPatchRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class DeploymentArtifactServiceImplTest { + + private DeploymentArtifactServiceImpl deploymentArtifactService; + + @Mock + private MsInstanceService msInstanceService; + + @Mock + private DeploymentArtifactGeneratorStrategy deploymentArtifactGeneratorStrategy; + + @Mock + private DeploymentArtifactGateway repository; + + @Mock + private ArtifactFileNameCreator fileNameCreator; + + @Mock + private DeploymentArtifactStatusChangeHandler deploymentArtifactStatusChangeHandler; + + private MsInstance msInstance; + + DeploymentArtifact deploymentArtifact; + + @BeforeEach + void setUp() { + //Initiated the deployment artifact core with mocks + deploymentArtifactService = new DeploymentArtifactServiceImpl(); + deploymentArtifactService.setDeploymentArtifactGeneratorStrategy(deploymentArtifactGeneratorStrategy); + deploymentArtifactService.setDeploymentArtifactGateway(repository); + deploymentArtifactService.setMsInstanceService(msInstanceService); + deploymentArtifactService.setFileNameCreator(fileNameCreator); + deploymentArtifactService.setStatusChangeHandler(deploymentArtifactStatusChangeHandler); + } + + private void setupMockBehaviours() { + //Mock methods + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + msInstance = MsInstanceObjectMother.createMsInstance(); + + when(deploymentArtifactGeneratorStrategy.generateForRelease(msInstance.getActiveSpec(), msInstance.getRelease())) + .thenReturn(DeploymentArtifactObjectMother.createBlueprintResponse()); + when(repository.save(any())).thenReturn(deploymentArtifact); + when(fileNameCreator.createFileName(any(MsInstance.class), any(Integer.class))).thenReturn(BASE_MS_TAG + "_" + + msInstance.getActiveSpec().getType().toString().toLowerCase() + "_" + msInstance.getRelease() + "_1.yaml"); + } + + @Test + void test_getAllDeploymentArtifactInstance() throws Exception{ + when(repository.findAll()).thenReturn(Arrays.asList(deploymentArtifact)); + List<DeploymentArtifact> deployments = deploymentArtifactService.getAllDeploymentArtifacts(); + assertThat(deployments.size()).isEqualTo(1); + } + + @Test + void test_GenerateBlueprint_shouldReturnCorrectBlueprint() throws Exception{ + + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + + //act + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + + //assert + verify(msInstanceService, atLeastOnce()).getMsInstanceById(MS_INSTANCE_ID); + verify(repository, times(1)).save(any()); + assertThat(resultDAO.getContent()).contains("tosca_definitions_version"); + assertThat(resultDAO.getId()).isNotEmpty(); + assertThat(resultDAO.getVersion()).isEqualTo(1); + assertThat(resultDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.IN_DEV); + assertThat(resultDAO.getMsInstanceInfo().getId()).isEqualTo(MS_INSTANCE_ID); + assertThat(resultDAO.getMsInstanceInfo().getName()).isEqualTo(msInstance.getName()); + assertThat(resultDAO.getMsInstanceInfo().getRelease()).isEqualTo(msInstance.getRelease()); + assertThat(resultDAO.getSpecificationInfo().get("id")).isNotNull(); + assertThat(resultDAO.getMetadata().get("createdBy")).isEqualTo(USER); + + } + + @Test + void test_deploymentVersionIsInitatedWith1() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(resultDAO.getVersion()).isEqualTo(1); + } + + @Test + void test_deploymentVersionIncrementsForEachAddForAnInstance() throws Exception{ + setupMockBehaviours(); + MsInstance msInstanceWithRef = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstanceWithRef); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + + assertThat(resultDAO.getVersion()).isEqualTo(2); + } + + @Test + void test_deploymentArtifactRefAddedToMsInstanceForFirstTime() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(msInstance.getDeploymentArtifactsInfo().getMostRecentVersion()).isEqualTo(1); + + List<String> deploymentArtifactList = msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts(); + assertThat(deploymentArtifactList.size()).isEqualTo(1); + assertThat(deploymentArtifactList.get(0)).isEqualTo(resultDAO.getId()); + } + + @Test + void test_deploymentArtifactRefAddedToMsInstanceForSecondTime() throws Exception{ + setupMockBehaviours(); + MsInstance msInstanceWithRef = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstanceWithRef); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(msInstanceWithRef.getDeploymentArtifactsInfo().getMostRecentVersion()).isEqualTo(2); + + List<String> deploymentArtifactList = msInstanceWithRef.getDeploymentArtifactsInfo().getDeploymentArtifacts(); + assertThat(deploymentArtifactList.size()).isEqualTo(2); + assertThat(deploymentArtifactList.get(1)).isEqualTo(resultDAO.getId()); + } + + @Test + void test_ifMsInstanceIsPersistedAfterDeploymentArtifactCreation() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + verify(msInstanceService, times(1)).updateMsInstance(msInstance); + } + + @Test + void test_blueprintFileNameValidation() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + System.out.println(resultDAO.getFileName()); + assertThat(resultDAO.getFileName().contains(BASE_MS_TAG)).isTrue(); + } + + @Test + void test_updateStatusForDeploymentArtifact() throws Exception{ + //arrange + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + DeploymentArtifactPatchRequest dtoWithStatus = new DeploymentArtifactPatchRequest(); + dtoWithStatus.setStatus(DeploymentArtifactStatus.NOT_NEEDED); + + when(repository.findById("id-123")).thenReturn(Optional.of(deploymentArtifact)); + + //Mocking void method from DeploymentArtifactStatusChangeHandler + doAnswer(invocation -> { + deploymentArtifact.setStatus(DeploymentArtifactStatus.NOT_NEEDED); + return null; + }).when(deploymentArtifactStatusChangeHandler).handleStatusChange(dtoWithStatus.getStatus(), deploymentArtifact); + + //act + deploymentArtifactService.updateDeploymentArtifact("id-123", dtoWithStatus, "user1"); + + //assert + assertThat(deploymentArtifact.getStatus()).isEqualTo(DeploymentArtifactStatus.NOT_NEEDED); + assertThat(deploymentArtifact.getMetadata().get("updatedBy")).isEqualTo("user1"); + assertThat(deploymentArtifact.getMetadata().get("updatedOn")).isNotNull(); + + verify(deploymentArtifactStatusChangeHandler, times(1)).handleStatusChange(dtoWithStatus.getStatus(), + deploymentArtifact); + verify(msInstanceService, times(1)). + updateStatusBasedOnDeploymentArtifactsStatuses(deploymentArtifact.getMsInstanceInfo().getId()); + verify(repository, times(1)).save(deploymentArtifact); + } + + @Test + void test_findDeploymentArtifactById() throws Exception{ + //arrange + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + when(repository.findById("id-123")).thenReturn(Optional.of(deploymentArtifact)); + + DeploymentArtifact result = deploymentArtifactService.findDeploymentArtifactById("id-123"); + + assertThat(result).isEqualTo(deploymentArtifact); + } + + @Test + void test_findByIdWithInvalidId() throws Exception{ + when(repository.findById("invalid-id")).thenReturn(Optional.empty()); + assertThatExceptionOfType(DeploymentArtifactNotFound.class).isThrownBy( + () -> deploymentArtifactService.findDeploymentArtifactById("invalid-id")); + } + + @Test + void test_deleteDeploymentArtifact() throws Exception{ + DeploymentArtifact deploymentArtifact = + DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + String id = deploymentArtifact.getId(); + + when(repository.findById(id)).thenReturn(Optional.of(deploymentArtifact)); + + deploymentArtifactService.deleteDeploymentArtifact(id); + verify(msInstanceService, times(1)) + .removeDeploymentArtifactFromMsInstance(deploymentArtifact); + verify(repository, times(1)).deleteById(id); + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java new file mode 100644 index 0000000..5e9acfa --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.StatusChangeNotValidException; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class DeploymentArtifactStatusChangeHandlerTest { + + DeploymentArtifactStatusChangeHandler artifactStatusChangeHandler; + + @Mock + DeploymentArtifactService deploymentArtifactService; + + @BeforeEach + void setUp() { + artifactStatusChangeHandler = new DeploymentArtifactStatusChangeHandler(); + artifactStatusChangeHandler.setDeploymentArtifactService(deploymentArtifactService); + } + + @Test + void test_DevCompleteToNotNeeded() throws Exception{ + //arrange + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true); + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + String msInstaneId = givenDAO.getMsInstanceInfo().getId(); + + when(deploymentArtifactService.findByMsInstanceId(msInstaneId)).thenReturn(mockDeploymentArticats); + + //act + artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.NOT_NEEDED, givenDAO); + + assertThat(givenDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.NOT_NEEDED); +// verify(msInstanceStatusChangeHandler, times(1)) +// .updateStatusBasedOnDeploymentArtifactsStatuses(msInstaneId); + + } + + @Test + void test_ValidateIfArtifactWithDevCompleteStatusNotFoundForTheSameInstance() throws Exception{ + //arrange + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + String msInstaneId = givenDAO.getMsInstanceInfo().getId(); + + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(false); + when(deploymentArtifactService.findByMsInstanceId(msInstaneId)).thenReturn(mockDeploymentArticats); + + //act + artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.DEV_COMPLETE, givenDAO); + + //assert + assertThat(givenDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.DEV_COMPLETE); + verify(deploymentArtifactService, times(1)). + findByMsInstanceId(givenDAO.getMsInstanceInfo().getId()); +// verify(msInstanceStatusChangeHandler, times(1)) +// .updateStatusBasedOnDeploymentArtifactsStatuses(msInstaneId); + + } + + @Test + void DoesntValidateIfArtifactWithDevCompleteStatusAlreadyExistsForTheSameInstance() throws Exception{ + //arrange + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true); + when(deploymentArtifactService.findByMsInstanceId("id-123")).thenReturn(mockDeploymentArticats); + + //act/assert + assertThatExceptionOfType(StatusChangeNotValidException.class).isThrownBy( + () -> artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.DEV_COMPLETE, givenDAO) + ); + + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java new file mode 100644 index 0000000..bc1a3a0 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java @@ -0,0 +1,90 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * 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.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class SearchDeploymentArtifactsTest { + + private DeploymentArtifactServiceImpl service; + + @Mock + private DeploymentArtifactGateway repository; + + private DeploymentArtifact artifact_1; + private DeploymentArtifact artifact_2; + private DeploymentArtifact artifact_3; + + @BeforeEach + void setUp() { + service = new DeploymentArtifactServiceImpl(); + service.setDeploymentArtifactGateway(repository); + + //given + artifact_1 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + artifact_1.getMsInstanceInfo().setRelease("2008"); + artifact_2 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + artifact_2.getMsInstanceInfo().setRelease("2010"); + artifact_3 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + artifact_3.getMsInstanceInfo().setRelease("2008"); + + } + +// @Test +// void findArtifacts_filteredWithRelease() throws Exception { +// List<DeploymentArtifact> artifacts = Arrays.asList(artifact_1, artifact_3); +// when(repository.findByReleaseOrStatusOfMsInstance("2008", null)).thenReturn(artifacts); +// +// //when +// DeploymentArtifactSearch search = new DeploymentArtifactSearch(); +// DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); +// filter.setRelease("2008"); +// search.setFilter(filter); +// +// List<DeploymentArtifact> result = core.searchDeploymentArtifacts(search); +// +// //assert +// assertThat(result.size()).isEqualTo(2); +// } +// +// @Test +// void findArtifacts_filteredWithStatus() throws Exception{ +// List<DeploymentArtifact> artifacts = Arrays.asList(artifact_2, artifact_3); +// when(repository.findByReleaseOrStatusOfMsInstance(null, DeploymentArtifactStatus.DEV_COMPLETE)) +// .thenReturn(artifacts); +// +// DeploymentArtifactSearch search = new DeploymentArtifactSearch(); +// DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); +// filter.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); +// search.setFilter(filter); +// +// List<DeploymentArtifact> result = core.searchDeploymentArtifacts(search); +// assertThat(result.size()).isEqualTo(2); +// +// } +} diff --git a/mod2/catalog-service/src/test/resources/application.properties b/mod2/catalog-service/src/test/resources/application.properties new file mode 100644 index 0000000..d6a913c --- /dev/null +++ b/mod2/catalog-service/src/test/resources/application.properties @@ -0,0 +1 @@ +#spring.data.mongodb.port=0
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationRequest.json b/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationRequest.json new file mode 100644 index 0000000..a0465d8 --- /dev/null +++ b/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationRequest.json @@ -0,0 +1,180 @@ +{ + "specContent": { + "self": { + "component_type": "docker", + "description": "Hello World mS for subscribing the data from local DMaaP, DR or MR, processing them and publishing them as PM files to local DMaaP DR", + "name": "dcae-collectors-vcc-helloworld-pm", + "version": "1.0.1" + }, + "services": { + "calls": [], + "provides": [] + }, + "streams": { + "publishes": [ + { + "config_key": "DCAE-HELLO-WORLD-PUB-DR", + "format": "dataformat_Hello_World_PM", + "type": "data_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-PUB-MR", + "format": "dataformat_Hello_World_PM", + "type": "message_router", + "version": "1.0.0" + } + ], + "subscribes": [ + { + "config_key": "DCAE-HELLO-WORLD-SUB-MR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE_HELLO_WORLD_SUB_MR", + "type": "message_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-SUB-DR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE-HELLO-WORLD-SUB-DR", + "type": "data_router", + "version": "1.0.0" + } + ] + }, + "parameters": [ + { + "name": "vcc_hello_name", + "value": "120", + "type": "integer", + "description": "the name entered for specific person", + "sourced_at_deployment": false, + "designer_editable": false, + "policy_editable": false + }, + { + "name": "useDtiConfig", + "value": false, + "type": "boolean", + "description": "component depends on configuration from dti.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required": true + }, + { + "name": "isSelfServeComponent", + "value": false, + "type": "boolean", + "description": "Is this used as self serve component.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required": true + } + ], + "auxilary": { + "healthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "livehealthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "reconfigs": { + "app_reconfig": "abc" + }, + "volumes": [ + { + "container": { + "bind": "/opt/app/dcae-certificate" + }, + "host": { + "path": "/opt/app/dcae-certificate" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/AGENT" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/AGENT" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/WATCHER" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/WATCHER" + } + }, + { + "container": { + "bind": "/opt/app/vcc/logs/DCAE" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/vcc-logs" + } + }, + { + "container": { + "bind": "/opt/app/vcc/archive/data" + }, + "host": { + "path": "/opt/data/DCAE/helloworldpm/vcc-archive" + } + } + ] + }, + "artifacts": [ + { + "type": "docker image", + "uri": "dockercentral.it.att.com:5100/com.att.sample/dcae-controller-vcc-helloworld-pm:18.02-001" + } + ] + }, + "policyJson": { + "policies": [ + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": false + }, + { + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": true + }, + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_*", + "unique": false + } + ], + "policy": [ + { + "policy_id": "id_0" + } + ] + }, + "type": "K8S", + "user": "abc123", + "metadata": { + "notes": "Sample 812-1", + "labels": [ + "LATEST" + ] + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationResponse.json b/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationResponse.json new file mode 100644 index 0000000..3cb6dcf --- /dev/null +++ b/mod2/catalog-service/src/test/resources/http/requests/CreateSpecificationResponse.json @@ -0,0 +1,188 @@ +{ + "id": "5f3417a26aef7f07bc91350a", + "status": "ACTIVE", + "specContent": { + "self": { + "component_type": "docker", + "description": "Hello World mS for subscribing the data from local DMaaP, DR or MR, processing them and publishing them as PM files to local DMaaP DR", + "name": "dcae-collectors-vcc-helloworld-pm", + "version": "1.0.1" + }, + "services": { + "calls": [], + "provides": [] + }, + "streams": { + "publishes": [ + { + "config_key": "DCAE-HELLO-WORLD-PUB-DR", + "format": "dataformat_Hello_World_PM", + "type": "data_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-PUB-MR", + "format": "dataformat_Hello_World_PM", + "type": "message_router", + "version": "1.0.0" + } + ], + "subscribes": [ + { + "config_key": "DCAE-HELLO-WORLD-SUB-MR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE_HELLO_WORLD_SUB_MR", + "type": "message_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-SUB-DR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE-HELLO-WORLD-SUB-DR", + "type": "data_router", + "version": "1.0.0" + } + ] + }, + "parameters": [ + { + "name": "vcc_hello_name", + "value": "120", + "type": "integer", + "description": "the name entered for specific person", + "sourced_at_deployment": false, + "designer_editable": false, + "policy_editable": false + }, + { + "name": "useDtiConfig", + "value": false, + "type": "boolean", + "description": "component depends on configuration from dti.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required": true + }, + { + "name": "isSelfServeComponent", + "value": false, + "type": "boolean", + "description": "Is this used as self serve component.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required": true + } + ], + "auxilary": { + "healthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "livehealthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "reconfigs": { + "app_reconfig": "abc" + }, + "volumes": [ + { + "container": { + "bind": "/opt/app/dcae-certificate" + }, + "host": { + "path": "/opt/app/dcae-certificate" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/AGENT" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/AGENT" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/WATCHER" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/WATCHER" + } + }, + { + "container": { + "bind": "/opt/app/vcc/logs/DCAE" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/vcc-logs" + } + }, + { + "container": { + "bind": "/opt/app/vcc/archive/data" + }, + "host": { + "path": "/opt/data/DCAE/helloworldpm/vcc-archive" + } + } + ] + }, + "artifacts": [ + { + "type": "docker image", + "uri": "dockercentral.it.att.com:5100/com.att.sample/dcae-controller-vcc-helloworld-pm:18.02-001" + } + ] + }, + "policyJson": { + "policies": [ + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": false + }, + { + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": true + }, + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_*", + "unique": false + } + ], + "policy": [ + { + "policy_id": "id_0" + } + ] + }, + "type": "K8S", + "metadata": { + "notes": "Sample 812-1", + "labels": [ + "LATEST" + ], + "createdBy": "abc123", + "createdOn": "2020-08-12T16:24:02.621+0000" + }, + "msInstanceInfo": { + "release": "2006", + "name": "hello-804", + "id": "5f1592ffb551b604628316b0" + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/resources/specification/componentSpec_hello_world-with-dmaap.json b/mod2/catalog-service/src/test/resources/specification/componentSpec_hello_world-with-dmaap.json new file mode 100644 index 0000000..0ad6b6e --- /dev/null +++ b/mod2/catalog-service/src/test/resources/specification/componentSpec_hello_world-with-dmaap.json @@ -0,0 +1,149 @@ +{ + "self": { + "component_type": "docker", + "description": "Hello World mS for subscribing the data from local DMaaP, DR or MR, processing them and publishing them as PM files to local DMaaP DR", + "name": "dcae-collectors-vcc-helloworld-pm", + "version": "1.0.1" + }, + + "services": { + "calls": [], + "provides": [] + }, + + "streams": { + "publishes": [{ + "config_key": "DCAE-HELLO-WORLD-PUB-DR", + "format": "dataformat_Hello_World_PM", + "type": "data_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-PUB-MR", + "format": "dataformat_Hello_World_PM", + "type": "message_router", + "version": "1.0.0" + } + ], + + "subscribes": [{ + "config_key": "DCAE-HELLO-WORLD-SUB-MR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE_HELLO_WORLD_SUB_MR", + "type": "message_router", + "version": "1.0.0" + }, + { + "config_key": "DCAE-HELLO-WORLD-SUB-DR", + "format": "dataformat_Hello_World_PM", + "route": "/DCAE-HELLO-WORLD-SUB-DR", + "type": "data_router", + "version": "1.0.0" + } + ] + }, + + "parameters": + [ + { + "name": "vcc_hello_name", + "value": "120", + "type": "integer", + "description": "the name entered for specific person", + "sourced_at_deployment": false, + "designer_editable": false, + "policy_editable": false + }, + + { + "name": "useDtiConfig", + "value": false, + "type" : "boolean", + "description": "component depends on configuration from dti.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required" : true + }, + + { + "name": "isSelfServeComponent", + "value": false, + "type": "boolean", + "description": "Is this used as self serve component.", + "sourced_at_deployment": false, + "designer_editable": true, + "policy_editable": false, + "required" : true + } + ], + + "auxilary": { + "healthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "livehealthcheck": { + "interval": "60s", + "initialDelaySeconds": "120s", + "timeout": "20s", + "script": "/opt/app/vcc/bin/common/HealthCheck_HelloWorld.sh", + "type": "docker" + }, + "reconfigs":{ + "app_reconfig" : "abc" + }, + + "volumes": [ + { + "container": { + "bind": "/opt/app/dcae-certificate" + }, + "host": { + "path": "/opt/app/dcae-certificate" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/AGENT" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/AGENT" + } + }, + { + "container": { + "bind": "/opt/logs/DCAE/dmd/WATCHER" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/dmd/WATCHER" + } + }, + { + "container": { + "bind": "/opt/app/vcc/logs/DCAE" + }, + "host": { + "path": "/opt/logs/DCAE/helloworldpm/vcc-logs" + } + }, + { + "container": { + "bind": "/opt/app/vcc/archive/data" + }, + "host": { + "path": "/opt/data/DCAE/helloworldpm/vcc-archive" + } + } + + ] + + }, + "artifacts": [{ + "type": "docker image", + "uri": "dockercentral.it.att.com:5100/com.att.sample/dcae-controller-vcc-helloworld-pm:18.02-001" + }] +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/resources/specification/policy_json_sample_3.json b/mod2/catalog-service/src/test/resources/specification/policy_json_sample_3.json new file mode 100644 index 0000000..4a8c76f --- /dev/null +++ b/mod2/catalog-service/src/test/resources/specification/policy_json_sample_3.json @@ -0,0 +1,28 @@ +{ + "policies": [ + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": false + }, + { + "onapName": "DCAE", + "policyName": "DCAE.Config_", + "unique": true + }, + { + "configAttributes": "", + "configName": "", + "onapName": "DCAE", + "policyName": "DCAE.Config_*", + "unique": false + } + ], + "policy": [ + { + "policy_id" : "id_0" + } + ] +}
\ No newline at end of file |