diff options
Diffstat (limited to 'ms')
11 files changed, 810 insertions, 41 deletions
diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt new file mode 100644 index 000000000..e3e5c26a3 --- /dev/null +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt @@ -0,0 +1,33 @@ +package org.onap.ccsdk.cds.controllerblueprints.core + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class BluePrintErrorTest { + + @Test + fun testBluePrintErrorIsCreatedWithemptyList() { + val bluePrintError = BluePrintError() + + assertTrue(bluePrintError.errors.isEmpty()) + } + + @Test + fun testAddErrorWith3Params() { + val bluePrintError = BluePrintError() + + bluePrintError.addError("type", "name", "error") + + assertEquals("type : name : error", bluePrintError.errors[0]) + } + + @Test + fun testAddErrorWith1Params() { + val bluePrintError = BluePrintError() + + bluePrintError.addError("error") + + assertEquals("error", bluePrintError.errors[0]) + } +}
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt index d5334dc5f..487b1d15b 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt @@ -16,8 +16,12 @@ package org.onap.ccsdk.cds.controllerblueprints.core +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.node.* import org.junit.Test -import kotlin.test.assertEquals +import kotlin.test.* + /** * * @@ -25,11 +29,172 @@ import kotlin.test.assertEquals */ class CustomFunctionsTest { @Test - fun testFormat(): Unit { + fun testFormat() { val returnValue : String = format("This is {} for times {}", "test", 2) assertEquals("This is test for times 2", returnValue, "Failed to format String") val returnValue1 : String = format("This is test for times 2") assertEquals("This is test for times 2", returnValue1, "Failed to format empty args") } + + @Test + fun testStringAsJsonPrimitive() { + val returnValue: TextNode = "hello".asJsonPrimitive() + assertEquals("hello", returnValue.textValue()) + } + + @Test + fun testIntAsJsonPrimitive() { + val returnValue: IntNode = 1.asJsonPrimitive() + assertEquals(1, returnValue.intValue()) + } + + @Test + fun testBooleanAsJsonPrimitive() { + val returnValue: BooleanNode = false.asJsonPrimitive() + assertFalse(returnValue.asBoolean()) + } + + @Test + fun testAsJsonType() { + val nullReturnValue: JsonNode = null.asJsonType() + assertEquals(NullNode.instance, nullReturnValue) + + val returnValueString: JsonNode = "hello".asJsonType() + assertEquals("hello", returnValueString.textValue()) + + val returnValueJsonNode: JsonNode = returnValueString.asJsonType() + assertEquals(returnValueString, returnValueJsonNode) + + val returnValueInt: JsonNode = 1.asJsonType() + assertEquals(1, returnValueInt.intValue()) + + val returnValueBool: JsonNode = false.asJsonType() + assertFalse(returnValueBool.asBoolean()) + + val returnValue: JsonNode = BluePrintError().asJsonType() + assertEquals(JsonNodeType.OBJECT, returnValue.getNodeType()) + } + + @Test + fun testMapAsObjectNode() { + val returnValue: ObjectNode = hashMapOf("test" to BluePrintError()).asObjectNode() + assertNotNull(returnValue.get("test")) + } + + @Test + fun testCastOptionalValue() { + val initMap: Map<String, *> = hashMapOf("test" to 1.1, "test2" to null) + val returnValue = initMap.castOptionalValue("test", Number::class) + + assert(returnValue is Number) + + val returnValueNull = initMap.castOptionalValue("test1", Number::class) + + assertNull(returnValueNull) + + val returnValueString: String? = initMap.castOptionalValue("test2", String::class) + + assertNull(returnValueString) + } + + @Test(expected = BluePrintException::class) + fun testCastValue() { + val initMap: Map<String, Double> = hashMapOf("test" to 1.1) + val returnValue = initMap.castValue("test", Number::class) + + assertNotNull(returnValue) + + initMap.castValue("test1", Number::class) + } + + @Test + fun testAsListOfString() { + val arrayNode: ArrayNode = ObjectMapper().createObjectNode().putArray("array") + + val result: List<String> = arrayNode.asListOfString() + + assertTrue(result.isEmpty()) + } + + @Test + fun testReturnNullIfMissing() { + val valueExist = "hello".asJsonType().returnNullIfMissing() + assertNotNull(valueExist) + + val valueNull = NullNode.instance.returnNullIfMissing() + assertNull(valueNull) + + val missingValue = MissingNode.getInstance().returnNullIfMissing() + assertNull(missingValue) + } + + @Test(expected = BluePrintException::class) + fun testRootFieldsToMap() { + 1.asJsonType().rootFieldsToMap() + } + + @Test + fun testPutJsonElement() { + val mutMap = mutableMapOf("test" to 2.asJsonType()) + + mutMap.putJsonElement("hello", 3) + + assertEquals(3, mutMap["hello"]?.asInt()) + } + + @Test(expected = BluePrintException::class) + fun testMapGetAsString() { + val initMap = hashMapOf("test" to "hello".asJsonType()) + + assertEquals("hello", initMap.getAsString("test")) + + initMap.getAsString("test2") + } + + @Test(expected = BluePrintException::class) + fun testMapGetAsBoolean() { + val initMap = hashMapOf("test" to true.asJsonType()) + + assertTrue(initMap.getAsBoolean("test")) + + initMap.getAsBoolean("test2") + } + + @Test(expected = BluePrintException::class) + fun testMapGetAsInt() { + val initMap = hashMapOf("test" to 1.asJsonType()) + + assertEquals(1, initMap.getAsInt("test")) + + initMap.getAsInt("test2") + } + + @Test(expected = BluePrintException::class) + fun testCheckEquals() { + assertTrue(checkEquals("hello", "hello", { -> "error"})) + + checkEquals("hello", "test", { -> "error"}) + } + + @Test(expected = IllegalStateException::class) + fun testCheckNotEmpty() { + assertEquals("hello", checkNotEmpty("hello", { -> "error"})) + + checkNotEmpty("", { -> "error"}) + } + + @Test(expected = IllegalStateException::class) + fun testCheckNotBlank() { + assertEquals("hello", checkNotBlank("hello", { -> "error"})) + + checkNotBlank(" ", { -> "error"}) + } + + @Test + fun testNullToEmpty() { + assertEquals("", nullToEmpty(null)) + + assertEquals("hello", nullToEmpty("hello")) + } }
\ No newline at end of file diff --git a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt index 2c6561f23..33890277f 100644 --- a/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt +++ b/ms/controllerblueprints/modules/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt @@ -18,11 +18,18 @@ package org.onap.ccsdk.cds.controllerblueprints.core.service +import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.* import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import kotlin.test.assertEquals import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue /** * @@ -49,5 +56,513 @@ class BluePrintContextTest { log.trace("Properties {}", JacksonUtils.getJson(nodeType, true)) } + @Test + fun testImports() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.imports = mutableListOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.imports()!!.isEmpty()) + + serviceTemplate.imports = null + assertNull(bluePrintContext.imports()) + } + + @Test + fun testDataTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.dataTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.dataTypes()!!.isEmpty()) + + serviceTemplate.dataTypes = null + assertNull(bluePrintContext.dataTypes()) + } + + @Test + fun testInputs() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.inputs = mutableMapOf() + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.inputs()!!.isEmpty()) + + topologyTemplate.inputs = null + + assertNull(bluePrintContext.inputs()) + } + + @Test + fun testBluePrintJson() { + val serviceTemplate = ServiceTemplate() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("{\"tosca_definitions_version\":\"controller_blueprint_1_0_0\"}", bluePrintContext.blueprintJson()) + } + + @Test(expected = BluePrintException::class) + fun testName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_NAME to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.name()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.name() + } + + @Test(expected = BluePrintException::class) + fun testVersion() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_VERSION to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.version()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.version() + } + + @Test(expected = BluePrintException::class) + fun testAuthor() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_AUTHOR to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.author()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.author() + } + + @Test + fun testWorkflows() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.workflows = mutableMapOf() + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.workflows()!!.isEmpty()) + + topologyTemplate.workflows = null + assertNull(bluePrintContext.workflows()) + } + + @Test(expected = BluePrintException::class) + fun testWorkFlowsByName() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.workflows = mutableMapOf("workflow" to Workflow()) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.workflowByName("workflow")) + + bluePrintContext.workflowByName("") + } + + @Test + fun testWorkflowInput() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + workflow.inputs = mutableMapOf() + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.workflowInputs("workflow")!!.isEmpty()) + + workflow.inputs = null + + assertNull(bluePrintContext.workflowInputs("workflow")) + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepByName() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + workflow.steps = mutableMapOf("step" to Step()) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.workflowStepByName("workflow", "step")) + + bluePrintContext.workflowStepByName("workflow", "") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepNodeTemplate() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + step.target = "hello" + workflow.steps = mutableMapOf("step" to step) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowStepNodeTemplate("workflow", "step")) + + bluePrintContext.workflowStepNodeTemplate("workflow", "") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowFirstStepNodeTemplate() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + step.target = "hello" + workflow.steps = mutableMapOf("step" to step, "step2" to Step()) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowFirstStepNodeTemplate("workflow")) + + workflow.steps = null + bluePrintContext.workflowFirstStepNodeTemplate("workflow") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepFirstCallOperation() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + val activity = Activity() + activity.callOperation = "hello" + step.activities = arrayListOf(activity) + workflow.steps = mutableMapOf("step" to step) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowStepFirstCallOperation("workflow", "step")) + + bluePrintContext.workflowStepFirstCallOperation("workflow", "") + } + + @Test + fun testDatatypeByName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.dataTypes = mutableMapOf("data" to DataType()) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.dataTypeByName("data")) + assertNull(bluePrintContext.dataTypeByName("")) + } + + @Test + fun testArtifactTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.artifactTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.artifactTypes()!!.isEmpty()) + + serviceTemplate.artifactTypes = null + assertNull(bluePrintContext.artifactTypes()) + } + + @Test + fun testPolicyTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.policyTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.policyTypes()!!.isEmpty()) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypes()) + } + + @Test(expected = BluePrintException::class) + fun testPolicyTypeByName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.policyTypes = mutableMapOf("policy" to PolicyType()) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.policyTypeByName("policy")) + bluePrintContext.policyTypeByName("") + } + + @Test + fun testPolicyTypesDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.derivedFrom = "hi" + val policyType2 = PolicyType() + policyType2.derivedFrom = "hello" + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesDerivedFrom("hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesDerivedFrom("hi")) + } + + @Test + fun testPolicyTypesTarget() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.targets = mutableListOf("hi") + val policyType2 = PolicyType() + policyType2.targets = mutableListOf() + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesTarget("hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesTarget("hi")) + } + + @Test + fun testPolicyTypesTargetNDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.targets = mutableListOf("hi") + policyType.derivedFrom = "hi" + val policyType2 = PolicyType() + policyType2.targets = mutableListOf() + policyType2.derivedFrom = "hi" + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")) + } + + @Test + fun testNodeTypeDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val nodeType = NodeType() + nodeType.derivedFrom = "hi" + val nodeType2 = NodeType() + nodeType2.derivedFrom = "hiii" + serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType, "node2" to nodeType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.nodeTypeDerivedFrom("hi")!!.size) + + serviceTemplate.nodeTypes = null + assertNull(bluePrintContext.nodeTypeDerivedFrom("hi")) + } + + @Test(expected = BluePrintException::class) + fun testInterfaceNameForNodeType() { + val serviceTemplate = ServiceTemplate() + val nodeType = NodeType() + nodeType.interfaces = mutableMapOf("hello" to InterfaceDefinition(), "hi" to InterfaceDefinition()) + serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.interfaceNameForNodeType("node")) + + bluePrintContext.interfaceNameForNodeType("") + } + + @Test + fun testNodeTemplateForNodeType() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.type = "hello" + val nodeTemplate2 = NodeTemplate() + nodeTemplate2.type = "hi" + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate, "node2" to nodeTemplate2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.nodeTemplateForNodeType("hello")!!.size) + + serviceTemplate.topologyTemplate!!.nodeTemplates = null + assertNull(bluePrintContext.nodeTemplateForNodeType("hello")) + } + + @Test + fun testNodeTemplateProperty() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateProperty("node", "prop")) + + assertNull(bluePrintContext.nodeTemplateProperty("node", "")) + + nodeTemplate.properties = null + assertNull(bluePrintContext.nodeTemplateProperty("node", "prop")) + } + + @Test + fun testNodeTemplateArtifacts() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.artifacts = mutableMapOf() + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.nodeTemplateArtifacts("node")!!.isEmpty()) + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateArtifact() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.artifacts = mutableMapOf("art" to ArtifactDefinition()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateArtifact("node", "art")) + + bluePrintContext.nodeTemplateArtifact("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateArtifactForArtifactType() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val artifactDefinition = ArtifactDefinition() + artifactDefinition.type = "type" + val artifactDefinition2 = ArtifactDefinition() + artifactDefinition2.type = "No type" + nodeTemplate.artifacts = mutableMapOf("art" to artifactDefinition, "art2" to artifactDefinition2) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateArtifactForArtifactType("node", "type")) + + bluePrintContext.nodeTemplateArtifactForArtifactType("", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterface() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateFirstInterface("node")) + + nodeTemplate.interfaces = null + bluePrintContext.nodeTemplateFirstInterface("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterfaceName() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("interface", bluePrintContext.nodeTemplateFirstInterfaceName("node")) + + nodeTemplate.interfaces = null + bluePrintContext.nodeTemplateFirstInterfaceName("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterfaceFirstOperationName() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = mutableMapOf("op" to OperationAssignment(), "op2" to OperationAssignment()) + nodeTemplate.interfaces = mutableMapOf("intf" to interfaceAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("op", bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node")) + + interfaceAssignment.operations = null + bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateCapability() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.capabilities = mutableMapOf("cap" to CapabilityAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateCapability("node", "cap")) + + bluePrintContext.nodeTemplateCapability("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateRequirement() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.requirements = mutableMapOf("req" to RequirementAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateRequirement("node", "req")) + + bluePrintContext.nodeTemplateRequirement("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateRequirementNode() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val requirementAssignment = RequirementAssignment() + requirementAssignment.node = "node" + nodeTemplate.requirements = mutableMapOf("req" to requirementAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateRequirementNode("node", "req")) + + bluePrintContext.nodeTemplateRequirementNode("node", "") + } + + @Test + fun testNodeTemplateCapabilityProperty() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val capabilityAssignment = CapabilityAssignment() + capabilityAssignment.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) + nodeTemplate.capabilities = mutableMapOf("cap" to capabilityAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) + + capabilityAssignment.properties = null + + assertNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) + } } diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java index eb339aef7..67db02e77 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java @@ -21,7 +21,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Objects; -import java.util.Optional; import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto; import org.onap.ccsdk.cds.sdclistener.service.ListenerService; import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus; @@ -102,26 +101,23 @@ public class SdcListenerNotificationCallback implements INotificationCallback { } } - public void processCsarArtifact(IDistributionClientDownloadResult result) { + private void processCsarArtifact(IDistributionClientDownloadResult result) { Path cbaArchivePath = Paths.get(pathToStoreArchives, "cba-archive"); Path csarArchivePath = Paths.get(pathToStoreArchives, "csar-archive"); // Extract and store the CSAR archive into local disk. - listenerService.extractCsarAndStore(result, csarArchivePath.toString()); + listenerService.extractCsarAndStore(result, csarArchivePath); - Optional<List<File>> csarFiles = FileUtil.getFilesFromDisk(csarArchivePath); + List<File> csarFiles = FileUtil.getFilesFromDisk(csarArchivePath); - if (csarFiles.isPresent()) { - //Extract CBA archive from CSAR package and store it into local disk. - List<File> files = csarFiles.get(); + if (!csarFiles.isEmpty()) { + final String archivePath = cbaArchivePath.toString(); - if (!files.isEmpty()) { - final String archivePath = cbaArchivePath.toString(); - files.forEach(file -> listenerService.extractBluePrint(file.getAbsolutePath(), archivePath)); - files.forEach(file -> FileUtil.deleteFile(file, archivePath)); - } else { - LOGGER.error("The CSAR file is not present at this location {}", csarArchivePath); - } + //Extract CBA archive from CSAR package and store it into local disk + csarFiles.forEach(file -> listenerService.extractBluePrint(file.getAbsolutePath(), archivePath)); + csarFiles.forEach(file -> FileUtil.deleteFile(file, csarArchivePath.toString())); + } else { + LOGGER.error("Could not able to read CSAR files from this location {}", csarArchivePath); } listenerService.saveBluePrintToCdsDatabase(cbaArchivePath, sdcListenerDto.getManagedChannelForGrpc()); diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java index 446c3e621..bc72c8f98 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java @@ -43,5 +43,5 @@ public interface ListenerService { * @param result - IDistributionClientDownloadResult contains payload. * @param csarArchivePath The destination path where CSAR will be stored. */ - void extractCsarAndStore(IDistributionClientDownloadResult result, String csarArchivePath); + void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath); } diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java index daab4de71..d1aac9704 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java @@ -35,14 +35,14 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FileUtils; import org.apache.tomcat.util.http.fileupload.IOUtils; +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput; +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk; import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto; import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler; import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus; import org.onap.ccsdk.cds.sdclistener.util.FileUtil; -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput; -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk; import org.onap.sdc.api.results.IDistributionClientDownloadResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -73,12 +73,14 @@ public class ListenerServiceImpl implements ListenerService { @Value("${listenerservice.config.grpcPort}") private int grpcPort; - private static final String CBA_ZIP_PATH = "Artifacts/Resources/[a-zA-Z0-9-_]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_]+[.]zip"; + private static final String CBA_ZIP_PATH = "Artifacts/[a-zA-Z0-9-_.]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_.()]+[.]zip"; private static final int SUCCESS_CODE = 200; private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class); @Override public void extractBluePrint(String csarArchivePath, String cbaArchivePath) { + int validPathCount = 0; + final String distributionId = sdcListenerDto.getDistributionId(); Path cbaStorageDir = getStorageDirectory(cbaArchivePath); try (ZipFile zipFile = new ZipFile(csarArchivePath)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); @@ -86,14 +88,24 @@ public class ListenerServiceImpl implements ListenerService { ZipEntry entry = entries.nextElement(); String fileName = entry.getName(); if (Pattern.matches(CBA_ZIP_PATH, fileName)) { + validPathCount++; final String cbaArchiveName = Paths.get(fileName).getFileName().toString(); LOGGER.info("Storing the CBA archive {}", cbaArchiveName); storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry); } } + if (validPathCount == 0) { + final String errorMessage = String + .format("The CBA Archive doesn't exist as per this given regex %s", CBA_ZIP_PATH); + listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_ERROR, errorMessage); + LOGGER.error(errorMessage); + } + } catch (Exception e) { - LOGGER.error("Failed to extract blueprint {}", e); + final String errorMessage = String.format("Failed to extract blueprint %s", e.getMessage()); + listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_ERROR, errorMessage); + LOGGER.error(errorMessage); } } @@ -119,15 +131,20 @@ public class ListenerServiceImpl implements ListenerService { @Override public void saveBluePrintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) { - Optional<List<File>> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath); - zipFiles.ifPresent(files -> prepareRequestForCdsBackend(files, channel, cbaArchivePath.toString())); + List<File> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath); + if (!zipFiles.isEmpty()) { + zipFiles.forEach(file -> FileUtil.deleteFile(file, cbaArchivePath.toString())); + prepareRequestForCdsBackend(zipFiles, channel, cbaArchivePath.toString()); + } else { + LOGGER.error("Could not able to read CBA archives from this location {}", cbaArchivePath); + } } @Override - public void extractCsarAndStore(IDistributionClientDownloadResult result, String csarArchivePath) { + public void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath) { // Create CSAR storage directory - Path csarStorageDir = getStorageDirectory(csarArchivePath); + Path csarStorageDir = getStorageDirectory(csarArchivePath.toString()); byte[] payload = result.getArtifactPayload(); String csarFileName = result.getArtifactFilename(); Path targetLocation = csarStorageDir.resolve(csarFileName); @@ -138,8 +155,11 @@ public class ListenerServiceImpl implements ListenerService { try (FileOutputStream outFile = new FileOutputStream(targetCsarFile)) { outFile.write(payload, 0, payload.length); + if (!csarArchivePath.toFile().exists()) { + LOGGER.error("Could not able to store the CSAR at this location {}", csarArchivePath); + } } catch (Exception e) { - LOGGER.error("Failed to put CSAR file into target location {}, {}", targetLocation, e); + LOGGER.error("Fail to write the data into FileOutputStream {}, {}", targetLocation, e); } } @@ -169,20 +189,17 @@ public class ListenerServiceImpl implements ListenerService { if (responseStatus.getCode() != SUCCESS_CODE) { final String errorMessage = String.format("Failed to store the CBA archive into CDS DB due to %s", responseStatus.getErrorMessage()); - listenerStatus.sendResponseStatusBackToSDC(distributionId, - COMPONENT_DONE_ERROR, errorMessage); + listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_ERROR, errorMessage); LOGGER.error(errorMessage); - } else { LOGGER.info(responseStatus.getMessage()); - listenerStatus.sendResponseStatusBackToSDC(distributionId, - COMPONENT_DONE_OK, null); + listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_OK, null); } } catch (Exception e) { final String errorMessage = String.format("Failure due to %s", e.getMessage()); listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_ERROR, errorMessage); - LOGGER.error("Failure due to {}", e); + LOGGER.error(errorMessage); } finally { FileUtil.deleteFile(zipFile, path); } diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/util/FileUtil.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/util/FileUtil.java index f2e679ecf..b6d0e4809 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/util/FileUtil.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/util/FileUtil.java @@ -20,8 +20,8 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FileUtils; @@ -54,15 +54,16 @@ public final class FileUtil { * @param path where files reside. * @return list of files. */ - public static Optional<List<File>> getFilesFromDisk(Path path) { + public static List<File> getFilesFromDisk(Path path) { + try (Stream<Path> fileTree = walk(path)) { // Get the list of files from the path - return Optional.of(fileTree.filter(Files::isRegularFile) - .map(Path::toFile) - .collect(Collectors.toList())); + return fileTree.filter(Files::isRegularFile) + .map(Path::toFile) + .collect(Collectors.toList()); } catch (IOException e) { LOGGER.error("Failed to find the file due to", e); } - return Optional.empty(); + return new ArrayList<>(); } } diff --git a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java index f5ff2bdb8..aed4b8b30 100644 --- a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java +++ b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java @@ -16,17 +16,25 @@ package org.onap.ccsdk.cds.sdclistener.service; import static junit.framework.TestCase.assertTrue; +import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_ERROR; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import mockit.Mock; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.internal.junit.JUnitRule; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.MockitoRule; import org.onap.ccsdk.cds.sdclistener.SdcListenerConfiguration; import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto; @@ -34,9 +42,11 @@ import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler; import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus; import org.onap.sdc.api.results.IDistributionClientDownloadResult; import org.onap.sdc.impl.mock.DistributionClientResultStubImpl; +import org.onap.sdc.utils.DistributionStatusEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @@ -46,23 +56,39 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = {ListenerServiceImplTest.class}) public class ListenerServiceImplTest { - private static final String CSAR_SAMPLE = "src/test/resources/service-Testsvc140.csar"; + private static final String CSAR_SAMPLE = "src/test/resources/service-ServicePnfTest-csar.csar"; + private static final String WRONG_CSAR_SAMPLE = "src/test/resources/wrong_csar_pattern.csar"; + private static final String CBA_ZIP_PATH = "Artifacts/[a-zA-Z0-9-_.]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_.()]+[.]zip"; private static final String ZIP_FILE = ".zip"; private static final String CSAR_FILE = ".csar"; + private static final String DISTRIBUTION_ID = "1"; + + private String csarArchivePath; private Path tempDirectoryPath; @Rule public TemporaryFolder folder = new TemporaryFolder(); + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Autowired private ListenerServiceImpl listenerService; + @MockBean + SdcListenerStatus status; + + @MockBean + SdcListenerDto listenerDto; + @Before public void setup() { + MockitoAnnotations.initMocks(this); csarArchivePath = folder.getRoot().toString(); tempDirectoryPath = Paths.get(csarArchivePath, "cds-sdc-listener-test"); } + @Test public void extractBluePrintSuccessfully() throws IOException { // Act @@ -74,12 +100,28 @@ public class ListenerServiceImplTest { } @Test + public void extractBluePrintFailure() { + // Arrange + final String errorMessage = String + .format("The CBA Archive doesn't exist as per this given regex %s", CBA_ZIP_PATH); + Mockito.when(listenerDto.getDistributionId()).thenReturn(DISTRIBUTION_ID); + Mockito.doCallRealMethod().when(status) + .sendResponseStatusBackToSDC(DISTRIBUTION_ID, COMPONENT_DONE_ERROR, errorMessage); + + // Act + listenerService.extractBluePrint(WRONG_CSAR_SAMPLE, tempDirectoryPath.toString()); + + // Verify + Mockito.verify(status).sendResponseStatusBackToSDC(DISTRIBUTION_ID, COMPONENT_DONE_ERROR, errorMessage); + } + + @Test public void storeCsarArtifactToFileSuccessfully() throws IOException { // Arrange DistributionClientDownloadResultStubImpl resultStub = new DistributionClientDownloadResultStubImpl(); // Act - listenerService.extractCsarAndStore(resultStub, tempDirectoryPath.toString()); + listenerService.extractCsarAndStore(resultStub, tempDirectoryPath); // Verify String result = checkFileExists(tempDirectoryPath); diff --git a/ms/sdclistener/application/src/test/resources/service-ServicePnfTest-csar.csar b/ms/sdclistener/application/src/test/resources/service-ServicePnfTest-csar.csar Binary files differnew file mode 100644 index 000000000..62a77dcaf --- /dev/null +++ b/ms/sdclistener/application/src/test/resources/service-ServicePnfTest-csar.csar diff --git a/ms/sdclistener/application/src/test/resources/service-Testsvc140.csar b/ms/sdclistener/application/src/test/resources/service-Testsvc140.csar Binary files differdeleted file mode 100644 index 4aa0de72b..000000000 --- a/ms/sdclistener/application/src/test/resources/service-Testsvc140.csar +++ /dev/null diff --git a/ms/sdclistener/application/src/test/resources/wrong_csar_pattern.csar b/ms/sdclistener/application/src/test/resources/wrong_csar_pattern.csar Binary files differnew file mode 100644 index 000000000..ee18b580d --- /dev/null +++ b/ms/sdclistener/application/src/test/resources/wrong_csar_pattern.csar |