Resolution processors tests and extendability 47/130447/10
authorLukasz Rajewski <lukasz.rajewski@t-mobile.pl>
Thu, 25 Aug 2022 22:23:01 +0000 (00:23 +0200)
committerLukasz Rajewski <lukasz.rajewski@t-mobile.pl>
Thu, 1 Sep 2022 13:50:43 +0000 (15:50 +0200)
- Open resolution processors for in-CBA customization
- Improve resolution tests verification
- Use RestProcessor for testing RestProcessor

Issue-ID: CCSDK-3716
Signed-off-by: Lukasz Rajewski <lukasz.rajewski@t-mobile.pl>
Change-Id: I7c05fc940647f40c20c37b4f7fcfe29f2c3076ba

12 files changed:
components/model-catalog/blueprint-model/test-blueprint/baseconfiguration/Definitions/resources_definition_types.json
ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBluePrintRestLibPropertyService.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBlueprintWebClientService.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessorTest.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt
ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessorTest.kt

index e679a9a..98f7726 100644 (file)
       "type": "string"
     },
     "updated-by": "Steve, Siani <steve.djissitchi@bell.ca>",
+    "sources": {
+      "aai-data": {
+        "type": "source-rest",
+        "properties": {
+          "type": "JSON",
+          "verb": "GET",
+          "url-path": "/aai/v22/network/generic-vnfs/generic-vnf/$vnf-id",
+          "path": "",
+          "input-key-mapping": {
+            "vnf-id": "vnf-id"
+          },
+          "output-key-mapping": {
+            "aai-get-resource": "vnf-id"
+          },
+          "key-dependencies": [
+            "vnf-id"
+          ]
+        }
+      }
+    }
+  },
+  "aai-get-resource-null": {
+    "tags": "aai-get",
+    "name": "aai-get-resource-null",
+    "property": {
+      "description": "primary aai data to get resource with empty content",
+      "type": "string"
+    },
+    "updated-by": "Rajewski, Lukasz <lukasz.rajewski@t-mobile.pl>",
+    "sources": {
+      "aai-data": {
+        "type": "source-rest",
+        "properties": {
+          "type": "JSON",
+          "verb": "GET",
+          "url-path": "/aai/v22/network/generic-vnfs/generic-vnf/$vnf-id",
+          "path": "",
+          "input-key-mapping": {
+            "vnf-id": "vnf-id"
+          },
+          "key-dependencies": [
+            "vnf-id"
+          ]
+        }
+      }
+    }
+  },
+  "aai-get-resource-wrong-mapping": {
+    "tags": "aai-get",
+    "name": "aai-get-resource-wrong-mapping",
+    "property": {
+      "description": "primary aai data to get resource with wrong mapping",
+      "type": "string"
+    },
+    "updated-by": "Rajewski, Lukasz <lukasz.rajewski@t-mobile.pl>",
+    "sources": {
+      "aai-data": {
+        "type": "source-rest",
+        "properties": {
+          "type": "JSON",
+          "verb": "GET",
+          "url-path": "/aai/v22/network/generic-vnfs/generic-vnf/$vnf-id",
+          "path": "",
+          "input-key-mapping": {
+            "vnf-id": "vnf-id"
+          },
+          "output-key-mapping": {
+            "aai-get-resource-wrong-mapping": "wrong"
+          },
+          "key-dependencies": [
+            "vnf-id"
+          ]
+        }
+      }
+    }
+  },
+  "aai-get-json-resource": {
+    "tags": "aai-get-json",
+    "name": "aai-get-json-resource",
+    "property": {
+      "description": "primary aai data to get resource",
+      "type": "json"
+    },
+    "updated-by": "Rajewski, Lukasz <lukasz.rajewski@t-mobile.pl>",
     "sources": {
       "aai-data": {
         "type": "source-rest",
index 9f318a3..f1692bb 100644 (file)
@@ -91,7 +91,7 @@ open class CapabilityResourceResolutionProcessor(private var componentFunctionSc
         ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, runtimeException.message)
     }
 
-    suspend fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List<String>):
+    open suspend fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List<String>):
         ResourceAssignmentProcessor {
 
             log.info("creating resource resolution of script type($scriptType), reference name($scriptClassReference)")
index 785f477..25d19cf 100644 (file)
@@ -78,7 +78,7 @@ open class DatabaseResourceAssignmentProcessor(
         }
     }
 
-    private fun setValueFromDB(resourceAssignment: ResourceAssignment) {
+    open fun setValueFromDB(resourceAssignment: ResourceAssignment) {
         val dName = resourceAssignment.dictionaryName!!
         val dSource = resourceAssignment.dictionarySource!!
         val resourceDefinition = resourceDefinition(dName)
@@ -119,7 +119,7 @@ open class DatabaseResourceAssignmentProcessor(
         populateResource(resourceAssignment, sourceProperties, rows)
     }
 
-    private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService {
+    open fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService {
         return if (isNotEmpty(sourceProperties.endpointSelector)) {
             val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!)
             bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson)
@@ -129,7 +129,7 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun validate(resourceAssignment: ResourceAssignment) {
+    open fun validate(resourceAssignment: ResourceAssignment) {
         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
         checkNotEmpty(resourceAssignment.dictionaryName) {
             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
@@ -140,12 +140,12 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     // placeholder to get the list of DB sources.
-    private fun getListOfDBSources(): Array<String> {
+    open fun getListOfDBSources(): Array<String> {
         return ResourceSourceMappingFactory.getRegisterSourceMapping()
             .resourceSourceMappings.filterValues { it == "source-db" }.keys.toTypedArray()
     }
 
-    private fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
+    open fun populateNamedParameter(inputKeyMapping: Map<String, String>): Map<String, Any> {
         val namedParameters = HashMap<String, Any>()
         inputKeyMapping.forEach {
             val expressionValue = raRuntimeService.getResolutionStore(it.value).textValue()
@@ -159,7 +159,7 @@ open class DatabaseResourceAssignmentProcessor(
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun populateResource(
+    open fun populateResource(
         resourceAssignment: ResourceAssignment,
         sourceProperties: DatabaseResourceSource,
         rows: List<Map<String, Any>>
index caf6b6a..dcf8801 100644 (file)
@@ -63,7 +63,7 @@ open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() {
     }
 
     // usecase: where input data attribute doesn't match with resourceName, and needs an alternate mapping provided under key-dependencies.
-    private fun setFromKeyDependencies(resourceAssignment: ResourceAssignment) {
+    open fun setFromKeyDependencies(resourceAssignment: ResourceAssignment) {
         val dName = resourceAssignment.dictionaryName!!
         val dSource = resourceAssignment.dictionarySource!!
         val resourceDefinition = resourceDefinition(dName)
index c075e1b..e96083f 100644 (file)
@@ -124,7 +124,7 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssig
         return true
     }
 
-    suspend fun executeScript(resourceAssignment: ResourceAssignment) {
+    open suspend fun executeScript(resourceAssignment: ResourceAssignment) {
         return when (scriptType) {
             BluePrintConstants.SCRIPT_JYTHON -> {
                 executeScriptBlocking(resourceAssignment)
@@ -198,7 +198,7 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode<ResourceAssig
         raRuntimeService.getBluePrintError().addError(error, getName())
     }
 
-    fun isTemplateKeyValueNull(resourceAssignment: ResourceAssignment): Boolean {
+    open fun isTemplateKeyValueNull(resourceAssignment: ResourceAssignment): Boolean {
         val resourceProp = checkNotNull(resourceAssignment.property) {
             "Failed to populate mandatory resource resource mapping $resourceAssignment"
         }
index de470d2..479be69 100644 (file)
@@ -141,7 +141,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS
         }
     }
 
-    fun blueprintWebClientService(
+    open fun blueprintWebClientService(
         resourceAssignment: ResourceAssignment,
         restResourceSource: RestResourceSource
     ): BlueprintWebClientService {
@@ -154,7 +154,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun populateResource(
+    open fun populateResource(
         resourceAssignment: ResourceAssignment,
         sourceProperties: RestResourceSource,
         restResponse: String,
@@ -216,7 +216,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS
     }
 
     @Throws(BluePrintProcessorException::class)
-    private fun validate(resourceAssignment: ResourceAssignment) {
+    open fun validate(resourceAssignment: ResourceAssignment) {
         checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" }
         checkNotEmpty(resourceAssignment.dictionaryName) {
             "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})"
index a2ec75d..5fb85da 100644 (file)
@@ -22,6 +22,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPrope
 class MockBluePrintRestLibPropertyService(bluePrintProperties: BluePrintPropertiesService) :
     BluePrintRestLibPropertyService(bluePrintProperties) {
 
+    private var services = mutableSetOf<MockBlueprintWebClientService>()
+
     fun mockBlueprintWebClientService(selector: String):
         MockBlueprintWebClientService {
             val prefix = "blueprintsprocessor.restclient.$selector"
@@ -31,6 +33,13 @@ class MockBluePrintRestLibPropertyService(bluePrintProperties: BluePrintProperti
 
     private fun mockBlueprintWebClientService(restClientProperties: RestClientProperties):
         MockBlueprintWebClientService {
-            return MockBlueprintWebClientService(restClientProperties)
+            val service = MockBlueprintWebClientService(restClientProperties)
+            services.add(service)
+            return service
         }
+
+    fun tearDown() {
+        services.forEach { it.tearDown() }
+        services.clear()
+    }
 }
index ba273e1..1e29f01 100644 (file)
@@ -36,6 +36,15 @@ class MockBlueprintWebClientService(private var restClientProperties: RestClient
     else restClientProperties.url.split(":")[2]
     private var headers: Map<String, String>
 
+    companion object {
+        const val JSON_OUTPUT: String = "{" +
+            "\"vnf-id\":\"123456\"," +
+            "\"param\": [{\"value\": \"vnf1\"}]," +
+            "\"vnf_name\":\"vnf1\"," +
+            "\"vnf-name\":\"vnf1\"" +
+            "}"
+    }
+
     init {
         mockServer = ClientAndServer.startClientAndServer(port.toInt())
         headers = defaultHeaders()
@@ -73,16 +82,19 @@ class MockBlueprintWebClientService(private var restClientProperties: RestClient
     override fun exchangeResource(
         method: String,
         path: String,
-        payload: String
+        payload: String,
+        headers: Map<String, String>
     ): BlueprintWebClientService.WebClientResponse<String> {
-        val header = arrayOf(BasicHeader(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
+        val header = arrayOf(BasicHeader(HttpHeaders.AUTHORIZATION, this.headers[HttpHeaders.AUTHORIZATION]))
         return when (method) {
             "POST" -> {
                 post(path, payload, header, String::class.java)
             }
+
             "PUT" -> {
                 put(path, payload, header, String::class.java)
             }
+
             else -> {
                 get(path, header, String::class.java)
             }
@@ -92,32 +104,36 @@ class MockBlueprintWebClientService(private var restClientProperties: RestClient
     private fun setRequest(method: String, path: String) {
         val requestResponse = when (method) {
             "POST" -> {
-                "Post response"
+                ""
             }
+
             "PUT" -> {
-                "Put response"
+                ""
             }
+
             else -> {
-                "Get response"
+                JSON_OUTPUT
             }
         }
         mockServer.`when`(
             request().withHeaders(Header(HttpHeaders.AUTHORIZATION, headers[HttpHeaders.AUTHORIZATION]))
                 .withMethod(method)
                 .withPath(path)
-        ).respond(response().withStatusCode(200).withBody("{\"aai-resource\":\"$requestResponse\"}"))
+        ).respond(response().withStatusCode(200).withBody(requestResponse))
     }
 
     private fun setRequestWithPayload(method: String, path: String, payload: String) {
         val requestResponse = when (method) {
             "POST" -> {
-                "Post response"
+                ""
             }
+
             "PUT" -> {
-                "Put response"
+                ""
             }
+
             else -> {
-                "Get response"
+                JSON_OUTPUT
             }
         }
         mockServer.`when`(
@@ -126,7 +142,7 @@ class MockBlueprintWebClientService(private var restClientProperties: RestClient
                 .withPath(path)
                 .withQueryStringParameter("format", "resource")
                 .withBody(payload)
-        ).respond(response().withStatusCode(200).withBody("{\"aai-resource\":\"$requestResponse\"}"))
+        ).respond(response().withStatusCode(200).withBody(requestResponse))
     }
 
     private fun setBasicAuth(username: String, password: String): String {
index 6909915..f9a41ce 100644 (file)
 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock
 
 import com.fasterxml.jackson.databind.JsonNode
-import com.fasterxml.jackson.databind.node.ArrayNode
 import org.apache.commons.collections.MapUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
-import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
-import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.RestResourceResolutionProcessor
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
-import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
-import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
 import org.slf4j.LoggerFactory
 import java.util.HashMap
@@ -34,7 +29,7 @@ import java.util.HashMap
 class MockRestResourceResolutionProcessor(
     private val blueprintRestLibPropertyService:
         MockBluePrintRestLibPropertyService
-) : ResourceAssignmentProcessor() {
+) : RestResourceResolutionProcessor(blueprintRestLibPropertyService) {
 
     private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)
 
@@ -53,128 +48,10 @@ class MockRestResourceResolutionProcessor(
         return "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
     }
 
-    override suspend fun processNB(executionRequest: ResourceAssignment) {
-        try {
-            // Check if It has Input
-            if (!setFromInput(executionRequest)) {
-                val dName = executionRequest.dictionaryName
-                val dSource = executionRequest.dictionarySource
-                val resourceDefinition = resourceDictionaries[dName]
-
-                val resourceSource = resourceDefinition!!.sources[dSource]
-
-                val resourceSourceProperties = resourceSource!!.properties
-
-                val sourceProperties =
-                    JacksonUtils.getInstanceFromMap(resourceSourceProperties!!, RestResourceSource::class.java)
-
-                val path = nullToEmpty(sourceProperties.path)
-                val inputKeyMapping = sourceProperties.inputKeyMapping
-
-                val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping!!).toMutableMap()
-
-                // Resolving content Variables
-                val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
-                val urlPath =
-                    resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
-                val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)
-
-                logger.info(
-                    "MockRestResource ($dSource) dictionary information: " +
-                        "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
-                )
-
-                // Get the Rest Client Service
-                val restClientService = blueprintWebClientService(executionRequest)
-
-                val response = restClientService.exchangeResource(verb, urlPath, payload)
-                val responseStatusCode = response.status
-                val responseBody = response.body
-                if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
-                    populateResource(executionRequest, sourceProperties, responseBody, path)
-                    restClientService.tearDown()
-                } else {
-                    val errMsg =
-                        "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
-                    logger.warn(errMsg)
-                    throw BluePrintProcessorException(errMsg)
-                }
-            }
-        } catch (e: Exception) {
-            ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
-            throw BluePrintProcessorException(
-                "Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}",
-                e
-            )
-        }
-    }
-
-    override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
-        addError(runtimeException.message!!)
-    }
-
-    private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
-        return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
-    }
-
-    @Throws(BluePrintProcessorException::class)
-    private fun populateResource(
+    override fun blueprintWebClientService(
         resourceAssignment: ResourceAssignment,
-        sourceProperties: RestResourceSource,
-        restResponse: String,
-        path: String
-    ) {
-        val type = nullToEmpty(resourceAssignment.property?.type)
-        lateinit var entrySchemaType: String
-
-        val outputKeyMapping = sourceProperties.outputKeyMapping
-
-        val responseNode = JacksonUtils.jsonNode(restResponse).at(path)
-
-        when (type) {
-            in BluePrintTypes.validPrimitiveTypes() -> {
-                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
-            }
-            in BluePrintTypes.validCollectionTypes() -> {
-                // Array Types
-                entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
-                val arrayNode = responseNode as ArrayNode
-
-                if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) {
-                    val responseArrayNode = responseNode.toList()
-                    for (responseSingleJsonNode in responseArrayNode) {
-
-                        val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
-
-                        outputKeyMapping!!.map {
-                            val responseKeyValue = responseSingleJsonNode.get(it.key)
-                            val propertyTypeForDataType = ResourceAssignmentUtils
-                                .getPropertyType(raRuntimeService, entrySchemaType, it.key)
-
-                            JacksonUtils.populateJsonNodeValues(
-                                it.value,
-                                responseKeyValue, propertyTypeForDataType, arrayChildNode
-                            )
-                        }
-                        arrayNode.add(arrayChildNode)
-                    }
-                }
-                // Set the List of Complex Values
-                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
-            }
-            else -> {
-                // Complex Types
-                entrySchemaType = resourceAssignment.property!!.type
-                val objectNode = JacksonUtils.objectMapper.createObjectNode()
-                outputKeyMapping!!.map {
-                    val responseKeyValue = responseNode.get(it.key)
-                    val propertyTypeForDataType = ResourceAssignmentUtils
-                        .getPropertyType(raRuntimeService, entrySchemaType, it.key)
-                    JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
-                }
-                // Set the List of Complex Values
-                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
-            }
-        }
+        restResourceSource: RestResourceSource
+    ): BlueprintWebClientService {
+        return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
     }
 }
index a109131..116d207 100644 (file)
  */
 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
 
+import com.fasterxml.jackson.databind.node.TextNode
 import kotlinx.coroutines.runBlocking
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
 import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
@@ -26,7 +28,8 @@ import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.test.context.ContextConfiguration
 import org.springframework.test.context.TestPropertySource
 import org.springframework.test.context.junit4.SpringRunner
-import kotlin.test.assertNotNull
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
 
 @RunWith(SpringRunner::class)
 @ContextConfiguration(classes = [DefaultResourceResolutionProcessor::class])
@@ -54,12 +57,17 @@ class DefaultResourceResolutionProcessorTest {
                 dictionarySource = "default"
                 property = PropertyDefinition().apply {
                     type = "string"
+                    defaultValue = TextNode("test")
+                    required = true
                 }
             }
 
-            val processorName = defaultResourceResolutionProcessor.applyNB(resourceAssignment)
-            assertNotNull(processorName, "couldn't get Default resource assignment processor name")
-            println(processorName)
+            val result = defaultResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "An error occurred while trying to test the DefaultResourceResolutionProcessor")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "An error occurred while trying to test the DefaultResourceResolutionProcessor"
+            )
         }
     }
 }
index cf8dc0c..0313c52 100644 (file)
@@ -24,6 +24,7 @@ import org.junit.Test
 import org.junit.runner.RunWith
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
 import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
@@ -31,6 +32,7 @@ import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.test.context.ContextConfiguration
 import org.springframework.test.context.TestPropertySource
 import org.springframework.test.context.junit4.SpringRunner
+import kotlin.test.assertEquals
 import kotlin.test.assertTrue
 
 @RunWith(SpringRunner::class)
@@ -65,11 +67,16 @@ class InputResourceResolutionProcessorTest {
                 dictionarySource = "input"
                 property = PropertyDefinition().apply {
                     type = "string"
+                    required = true
                 }
             }
 
-            val operationOutcome = inputResourceResolutionProcessor.applyNB(resourceAssignment)
-            assertTrue(operationOutcome, "An error occurred while trying to test the InputResourceResolutionProcessor")
+            val result = inputResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "An error occurred while trying to test the InputResourceResolutionProcessor")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "An error occurred while trying to test the InputResourceResolutionProcessor"
+            )
         }
     }
 }
index cb72141..56ce3f6 100644 (file)
@@ -15,6 +15,7 @@
  */
 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor
 
+import com.fasterxml.jackson.databind.JsonNode
 import kotlinx.coroutines.runBlocking
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -22,18 +23,24 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
 import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBluePrintRestLibPropertyService
+import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBlueprintWebClientService
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockRestResourceResolutionProcessor
 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
 import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
 import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
 import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.test.context.ContextConfiguration
 import org.springframework.test.context.TestPropertySource
 import org.springframework.test.context.junit4.SpringRunner
+import kotlin.test.AfterTest
 import kotlin.test.BeforeTest
-import kotlin.test.assertNotNull
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
 
 @RunWith(SpringRunner::class)
 @ContextConfiguration(
@@ -53,10 +60,6 @@ class RestResourceResolutionProcessorTest {
     @BeforeTest
     fun init() {
         restResourceResolutionProcessor = MockRestResourceResolutionProcessor(bluePrintRestLibPropertyService)
-    }
-
-    @Test
-    fun `test rest resource resolution`() {
         runBlocking {
             val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
                 "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
@@ -73,75 +76,181 @@ class RestResourceResolutionProcessorTest {
             scriptPropertyInstances["mock-service2"] = MockCapabilityService()
 
             restResourceResolutionProcessor.scriptPropertyInstances = scriptPropertyInstances
+        }
+    }
 
+    @AfterTest
+    fun tearDown() {
+        bluePrintRestLibPropertyService.tearDown()
+    }
+
+    private fun getExpectedJsonResponse(field: String? = null): JsonNode {
+        val node = JacksonUtils.jsonNode(MockBlueprintWebClientService.JSON_OUTPUT)
+        return if (field != null)
+            node.get(field)
+        else
+            node
+    }
+
+    @Test
+    fun `test rest resource resolution sdnc`() {
+        runBlocking {
             val resourceAssignment = ResourceAssignment().apply {
-                name = "rr-name"
+                name = "vnf_name"
                 dictionaryName = "vnf_name"
                 dictionarySource = "sdnc"
                 property = PropertyDefinition().apply {
                     type = "string"
+                    required = true
                 }
             }
 
-            val processorName = restResourceResolutionProcessor.applyNB(resourceAssignment)
-            assertNotNull(processorName, "couldn't get Rest resource assignment processor name")
-            println(processorName)
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "get Rest resource assignment failed")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "get Rest resource assignment failed"
+            )
+            val value = restResourceResolutionProcessor.raRuntimeService.getResolutionStore(resourceAssignment.name)
+            println("Resolution result: $result, status: ${resourceAssignment.status}, value: ${value.asText()}")
+            assertEquals(
+                getExpectedJsonResponse(resourceAssignment.name).asText(),
+                value.asText(),
+                "get Rest resource assignment failed - enexpected value"
+            )
         }
     }
 
     @Test
-    fun `test rest aai get resource resolution`() {
+    fun `test rest resource resolution get required fails`() {
         runBlocking {
-            val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
-                "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+            val resourceAssignment = ResourceAssignment().apply {
+                name = "rr-aai-empty"
+                dictionaryName = "aai-get-resource-null"
+                dictionarySource = "aai-data"
+                property = PropertyDefinition().apply {
+                    type = "string"
+                    required = true
+                }
+            }
+
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertFalse(result, "get Rest resource assignment succeeded while it should fail")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_FAILURE,
+                "get Rest resource assignment succeeded while it should fail"
             )
+            println("Resolution result: $result, status: ${resourceAssignment.status}")
+        }
+    }
 
-            val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
+    @Test
+    fun `test rest resource resolution get with wrong mapping fails`() {
+        runBlocking {
+            val resourceAssignment = ResourceAssignment().apply {
+                name = "rr-aai-wrong-mapping"
+                dictionaryName = "aai-get-resource-wrong-mapping"
+                dictionarySource = "aai-data"
+                property = PropertyDefinition().apply {
+                    type = "string"
+                    required = false
+                }
+            }
 
-            restResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
-            restResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils
-                .resourceDefinitions(bluePrintContext.rootPath)
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertFalse(result, "get Rest resource assignment succeeded while it should fail")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_FAILURE,
+                "get Rest resource assignment succeeded while it should fail"
+            )
+            println("Resolution result: $result, status: ${resourceAssignment.status}")
+        }
+    }
 
-            val scriptPropertyInstances: MutableMap<String, Any> = mutableMapOf()
-            scriptPropertyInstances["mock-service1"] = MockCapabilityService()
-            scriptPropertyInstances["mock-service2"] = MockCapabilityService()
+    @Test
+    fun `test rest resource resolution get without output mapping`() {
+        runBlocking {
+            val resourceAssignment = ResourceAssignment().apply {
+                name = "rr-aai-empty"
+                dictionaryName = "aai-get-resource-null"
+                dictionarySource = "aai-data"
+                property = PropertyDefinition().apply {
+                    type = "string"
+                    required = false
+                }
+            }
 
-            restResourceResolutionProcessor.scriptPropertyInstances = scriptPropertyInstances
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "get Rest resource assignment failed")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "get Rest resource assignment failed"
+            )
+            println("Resolution result: $result, status: ${resourceAssignment.status}")
+        }
+    }
 
+    @Test
+    fun `test rest resource resolution aai get string`() {
+        runBlocking {
             val resourceAssignment = ResourceAssignment().apply {
-                name = "rr-aai"
+                name = "vnf-id"
                 dictionaryName = "aai-get-resource"
                 dictionarySource = "aai-data"
                 property = PropertyDefinition().apply {
                     type = "string"
+                    required = true
                 }
             }
 
-            val processorName = restResourceResolutionProcessor.applyNB(resourceAssignment)
-            assertNotNull(processorName, "couldn't get AAI Rest resource assignment processor name")
-            println(processorName)
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "get AAI string Rest resource assignment failed")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "get AAI string Rest resource assignment failed"
+            )
+            val value = restResourceResolutionProcessor.raRuntimeService.getResolutionStore(resourceAssignment.name)
+            println("Resolution result: $result, status: ${resourceAssignment.status}, value: ${value.asText()}")
+            assertEquals(
+                getExpectedJsonResponse(resourceAssignment.name).asText(),
+                value.asText(),
+                "get Rest resource assignment failed - enexpected value"
+            )
         }
     }
 
     @Test
-    fun `test rest aai put resource resolution`() {
+    fun `test rest resource resolution aai get json`() {
         runBlocking {
-            val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(
-                "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
-            )
-
-            val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext)
-
-            restResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService
-            restResourceResolutionProcessor.resourceDictionaries = ResourceAssignmentUtils
-                .resourceDefinitions(bluePrintContext.rootPath)
-
-            val scriptPropertyInstances: MutableMap<String, Any> = mutableMapOf()
-            scriptPropertyInstances["mock-service1"] = MockCapabilityService()
-            scriptPropertyInstances["mock-service2"] = MockCapabilityService()
+            val resourceAssignment = ResourceAssignment().apply {
+                name = "generic-vnf"
+                dictionaryName = "aai-get-json-resource"
+                dictionarySource = "aai-data"
+                property = PropertyDefinition().apply {
+                    type = "json"
+                    required = true
+                }
+            }
 
-            restResourceResolutionProcessor.scriptPropertyInstances = scriptPropertyInstances
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "get AAI json Rest resource assignment failed")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "get AAI json Rest resource assignment failed"
+            )
+            val value = restResourceResolutionProcessor.raRuntimeService.getResolutionStore(resourceAssignment.name)
+            println("Resolution result: $result, status: ${resourceAssignment.status}, value: ${value.toPrettyString()}")
+            assertEquals(
+                getExpectedJsonResponse().toPrettyString(),
+                value.toPrettyString(),
+                "get Rest resource assignment failed - enexpected value"
+            )
+        }
+    }
 
+    @Test
+    fun `test rest resource resolution aai put`() {
+        runBlocking {
             val resourceAssignment = ResourceAssignment().apply {
                 name = "rr-aai"
                 dictionaryName = "aai-put-resource"
@@ -151,9 +260,13 @@ class RestResourceResolutionProcessorTest {
                 }
             }
 
-            val processorName = restResourceResolutionProcessor.applyNB(resourceAssignment)
-            assertNotNull(processorName, "couldn't get AAI Rest resource assignment processor name")
-            println(processorName)
+            val result = restResourceResolutionProcessor.applyNB(resourceAssignment)
+            assertTrue(result, "put AAI Rest resource assignment failed")
+            assertEquals(
+                resourceAssignment.status, BluePrintConstants.STATUS_SUCCESS,
+                "put AAI json Rest resource assignment failed"
+            )
+            println("Resolution result: $result, status: ${resourceAssignment.status}")
         }
     }
 }