Fix - ResolutionSummary should contain resolved request-payload
[ccsdk/cds.git] / ms / blueprintsprocessor / functions / resource-resolution / src / test / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / functions / resource / resolution / utils / ResourceAssignmentUtilsTest.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * Modifications Copyright (c) 2019 IBM, Bell Canada.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils
23
24 import com.fasterxml.jackson.databind.JsonNode
25 import com.fasterxml.jackson.databind.node.TextNode
26 import io.mockk.every
27 import io.mockk.spyk
28 import kotlinx.coroutines.runBlocking
29 import org.junit.Before
30 import org.junit.Test
31 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService
32 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
33 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType
34 import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
35 import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema
36 import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
37 import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
38 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
39 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
40 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
41 import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
42 import kotlin.test.assertEquals
43
44 data class IpAddress(val port: String, val ip: String)
45 data class Host(val name: String, val ipAddress: IpAddress)
46 data class ExpectedResponseIp(val ip: String)
47 data class ExpectedResponseIpAddress(val ipAddress: IpAddress)
48
49 class ResourceAssignmentUtilsTest {
50     private lateinit var resourceAssignmentRuntimeService: ResourceAssignmentRuntimeService
51     private lateinit var resourceAssignment: ResourceAssignment
52
53     private lateinit var inputMapToTestPrimitiveTypeWithValue: JsonNode
54     private lateinit var inputMapToTestPrimitiveTypeWithKeyValue: JsonNode
55     private lateinit var inputMapToTestCollectionOfPrimitiveType: JsonNode
56     private lateinit var inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping: JsonNode
57     private lateinit var inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping: JsonNode
58     private lateinit var inputMapToTestComplexTypeWithOneOutputKeyMapping: JsonNode
59     private lateinit var inputMapToTestComplexTypeWithAllOutputKeyMapping: JsonNode
60     private lateinit var expectedValueToTestPrimitiveType: JsonNode
61     private lateinit var expectedValueToTesCollectionOfPrimitiveType: JsonNode
62     private lateinit var expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping: JsonNode
63     private lateinit var expectedValueToTestComplexTypeWithOneOutputKeyMapping: JsonNode
64     private lateinit var expectedValueToTestComplexTypeWithAllOutputKeyMapping: JsonNode
65     private lateinit var expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping: JsonNode
66
67     @Before
68     fun setup() {
69
70         val bluePrintContext = runBlocking {
71             BluePrintMetadataUtils.getBluePrintContext(
72                 "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
73             )
74         }
75
76         resourceAssignmentRuntimeService = spyk(ResourceAssignmentRuntimeService("1234", bluePrintContext))
77
78         // Init input map and expected values for tests
79         initInputMapAndExpectedValuesForPrimitiveType()
80         initInputMapAndExpectedValuesForCollection()
81         initInputMapAndExpectedValuesForComplexType()
82
83         val propertiesDefinition1 = PropertyDefinition().apply {
84             type = "string"
85             id = "port"
86         }
87
88         val propertiesDefinition2 = PropertyDefinition().apply {
89             type = "string"
90             id = "ip"
91         }
92
93         val propertiesDefinition3 = PropertyDefinition().apply {
94             type = "string"
95             id = "name"
96         }
97
98         val propertiesDefinition4 = PropertyDefinition().apply {
99             type = "ip-address"
100             id = "ipAddress"
101         }
102
103         val mapOfPropertiesIpAddress = mutableMapOf<String, PropertyDefinition>()
104         mapOfPropertiesIpAddress["port"] = propertiesDefinition1
105         mapOfPropertiesIpAddress["ip"] = propertiesDefinition2
106
107         val mapOfPropertiesHost = mutableMapOf<String, PropertyDefinition>()
108         mapOfPropertiesHost["name"] = propertiesDefinition3
109         mapOfPropertiesHost["ipAddress"] = propertiesDefinition4
110
111         val myDataTypeIpaddress = DataType().apply {
112             id = "ip-address"
113             properties = mapOfPropertiesIpAddress
114         }
115
116         val myDataTypeHost = DataType().apply {
117             id = "host"
118             properties = mapOfPropertiesHost
119         }
120
121         every {
122             resourceAssignmentRuntimeService.bluePrintContext().dataTypeByName("ip-address")
123         } returns myDataTypeIpaddress
124
125         every { resourceAssignmentRuntimeService.bluePrintContext().dataTypeByName("host") } returns myDataTypeHost
126
127         every { resourceAssignmentRuntimeService.setNodeTemplateAttributeValue(any(), any(), any()) } returns Unit
128     }
129
130     @Test
131     fun `generateResourceDataForAssignments - positive test`() {
132         // given a valid resource assignment
133         val validResourceAssignment = createResourceAssignmentForTest("valid_value")
134
135         // and a list containing that resource assignment
136         val resourceAssignmentList = listOf<ResourceAssignment>(validResourceAssignment)
137
138         // when the values of the resources are evaluated
139         val outcome = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignmentList)
140
141         // then the assignment should produce a valid result
142         val expected = "{\n" + "  \"pnf-id\" : \"valid_value\"\n" + "}"
143         assertEquals(expected, outcome.replace("\r\n", "\n"), "unexpected outcome generated")
144     }
145
146     @Test
147     fun `generateResourceDataForAssignments - resource without value is not resolved as null`() {
148         // given a valid resource assignment
149         val resourceAssignmentWithNullValue = createResourceAssignmentForTest(null)
150
151         // and a list containing that resource assignment
152         val resourceAssignmentList = listOf<ResourceAssignment>(resourceAssignmentWithNullValue)
153
154         // when the values of the resources are evaluated
155         val outcome = ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignmentList)
156
157         // then the assignment should produce a valid result
158         val expected = "{\n" + "  \"pnf-id\" : \"\${pnf-id}\"\n" + "}"
159         assertEquals(expected, outcome.replace("\r\n", "\n"), "unexpected outcome generated")
160     }
161
162     @Test
163     fun generate() {
164         val resourceAssignment = createResourceAssignmentForTest(null)
165         val resourceDefinition = ResourceDefinition()
166         val nodeTemplate = NodeTemplate().apply {
167             properties = mutableMapOf("resolved-payload" to JacksonUtils.jsonNode("{\"mock\": true}"))
168         }
169         resourceDefinition.sources = mutableMapOf("input" to nodeTemplate)
170
171         val result = ResourceAssignmentUtils.generateResolutionSummaryData(
172                 listOf(resourceAssignment), mapOf("pnf-id" to resourceDefinition))
173
174         assertEquals("""
175             [{
176                 "name":"pnf-id",
177                 "value":null,
178                 "required":null,
179                 "type":"string",
180                 "key-identifiers":[],
181                 "dictionary-name":"pnf-id",
182                 "request-payload":{"mock":true},
183                 "dictionary-source":"input",
184                 "status":null,
185                 "message":null
186             }]
187         """.replace("\n|\\s".toRegex(), ""), result)
188     }
189
190     private fun createResourceAssignmentForTest(resourceValue: String?): ResourceAssignment {
191         val valueForTest = if (resourceValue == null) null else TextNode(resourceValue)
192         val resourceAssignmentForTest = ResourceAssignment().apply {
193             name = "pnf-id"
194             dictionaryName = "pnf-id"
195             dictionarySource = "input"
196             property = PropertyDefinition().apply {
197                 type = "string"
198                 value = valueForTest
199             }
200         }
201         return resourceAssignmentForTest
202     }
203
204     @Test
205     fun parseResponseNodeTestForPrimitivesTypes() {
206         var outcome = prepareResponseNodeForTest(
207             "sample-value", "string", "",
208             inputMapToTestPrimitiveTypeWithValue
209         )
210         assertEquals(
211             expectedValueToTestPrimitiveType,
212             outcome,
213             "Unexpected outcome returned for primitive type of simple String"
214         )
215         assertEquals(0, resourceAssignment.keyIdentifiers.size)
216
217         outcome = prepareResponseNodeForTest(
218             "sample-key-value", "string", "",
219             inputMapToTestPrimitiveTypeWithKeyValue
220         )
221         assertEquals(
222             expectedValueToTestPrimitiveType,
223             outcome,
224             "Unexpected outcome returned for primitive type of key-value String"
225         )
226         assertEquals(
227                 expectedValueToTestPrimitiveType,
228                 resourceAssignment.keyIdentifiers[0].value
229         )
230     }
231
232     @Test
233     fun parseResponseNodeTestForCollectionsOfString() {
234         var outcome = prepareResponseNodeForTest(
235             "listOfString", "list",
236             "string", inputMapToTestCollectionOfPrimitiveType
237         )
238         assertEquals(
239             expectedValueToTesCollectionOfPrimitiveType,
240             outcome,
241             "unexpected outcome returned for list of String"
242         )
243
244         val expectedKeyIdentifierValue = JacksonUtils.getJsonNode(outcome.map { it["ip"] })
245         assertEquals(
246                 expectedKeyIdentifierValue,
247                 resourceAssignment.keyIdentifiers[0].value
248         )
249
250         // FIXME("Map is not collection type, It is known complex type")
251         // outcome = prepareResponseNodeForTest(
252         //     "mapOfString", "map", "string",
253         //     inputMapToTestCollectionOfPrimitiveType
254         // )
255         // assertEquals(
256         //     expectedValueToTesCollectionOfPrimitiveType,
257         //     outcome,
258         //     "unexpected outcome returned for map of String"
259         // )
260     }
261
262     @Test
263     fun parseResponseNodeTestForCollectionsOfComplexType() {
264         var outcome = prepareResponseNodeForTest(
265             "listOfMyDataTypeWithOneOutputKeyMapping", "list",
266             "ip-address", inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping
267         )
268         assertEquals(
269             expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping,
270             outcome,
271             "unexpected outcome returned for list of String"
272         )
273
274         outcome = prepareResponseNodeForTest(
275             "listOfMyDataTypeWithAllOutputKeyMapping", "list",
276             "ip-address", inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping
277         )
278         assertEquals(
279             expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping,
280             outcome,
281             "unexpected outcome returned for list of String"
282         )
283     }
284
285     @Test
286     fun `parseResponseNodeTestForComplexType find one output key mapping`() {
287         val outcome = prepareResponseNodeForTest(
288             "complexTypeOneKeys", "host",
289             "", inputMapToTestComplexTypeWithOneOutputKeyMapping
290         )
291         assertEquals(
292             expectedValueToTestComplexTypeWithOneOutputKeyMapping,
293             outcome,
294             "Unexpected outcome returned for complex type"
295         )
296         assertEquals(
297                 expectedValueToTestComplexTypeWithOneOutputKeyMapping["host"],
298                 resourceAssignment.keyIdentifiers[0].value)
299     }
300
301     @Test
302     fun `parseResponseNodeTestForComplexType find all output key mapping`() {
303         val outcome = prepareResponseNodeForTest(
304             "complexTypeAllKeys", "host",
305             "", inputMapToTestComplexTypeWithAllOutputKeyMapping
306         )
307         assertEquals(
308             expectedValueToTestComplexTypeWithAllOutputKeyMapping,
309             outcome,
310             "Unexpected outcome returned for complex type"
311         )
312         assertEquals(2, resourceAssignment.keyIdentifiers.size)
313         assertEquals(
314                 expectedValueToTestComplexTypeWithAllOutputKeyMapping["name"],
315                 resourceAssignment.keyIdentifiers[0].value
316         )
317
318         assertEquals(
319                 expectedValueToTestComplexTypeWithAllOutputKeyMapping["ipAddress"],
320                 resourceAssignment.keyIdentifiers[1].value
321         )
322     }
323
324     private fun initInputMapAndExpectedValuesForPrimitiveType() {
325         inputMapToTestPrimitiveTypeWithValue = "1.2.3.1".asJsonType()
326         val keyValue = mutableMapOf<String, String>()
327         keyValue["value"] = "1.2.3.1"
328         inputMapToTestPrimitiveTypeWithKeyValue = keyValue.asJsonType()
329         expectedValueToTestPrimitiveType = TextNode("1.2.3.1")
330     }
331
332     private fun initInputMapAndExpectedValuesForCollection() {
333         val listOfIps = arrayListOf("1.2.3.1", "1.2.3.2", "1.2.3.3")
334         val arrayNodeForList1 = JacksonUtils.objectMapper.createArrayNode()
335         listOfIps.forEach {
336             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
337             arrayChildNode.set<JsonNode>("value", it.asJsonPrimitive())
338             arrayNodeForList1.add(arrayChildNode)
339         }
340         inputMapToTestCollectionOfPrimitiveType = arrayNodeForList1
341
342         expectedValueToTesCollectionOfPrimitiveType = arrayListOf(
343             ExpectedResponseIp("1.2.3.1"),
344             ExpectedResponseIp("1.2.3.2"), ExpectedResponseIp("1.2.3.3")
345         ).asJsonType()
346
347         val listOfIpAddresses = arrayListOf(
348             IpAddress("1111", "1.2.3.1").asJsonType(),
349             IpAddress("2222", "1.2.3.2").asJsonType(), IpAddress("3333", "1.2.3.3").asJsonType()
350         )
351         val arrayNodeForList2 = JacksonUtils.objectMapper.createArrayNode()
352         listOfIpAddresses.forEach {
353             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
354             arrayChildNode.set<JsonNode>("value", it.asJsonType())
355             arrayNodeForList2.add(arrayChildNode)
356         }
357         inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayNodeForList2
358
359         val arrayNodeForList3 = JacksonUtils.objectMapper.createArrayNode()
360         var childNode = JacksonUtils.objectMapper.createObjectNode()
361         childNode.set<JsonNode>("port", "1111".asJsonPrimitive())
362         childNode.set<JsonNode>("ip", "1.2.3.1".asJsonPrimitive())
363         arrayNodeForList3.add(childNode)
364         childNode = JacksonUtils.objectMapper.createObjectNode()
365         childNode.set<JsonNode>("port", "2222".asJsonPrimitive())
366         childNode.set<JsonNode>("ip", "1.2.3.2".asJsonPrimitive())
367         arrayNodeForList3.add(childNode)
368         childNode = JacksonUtils.objectMapper.createObjectNode()
369         childNode.set<JsonNode>("port", "3333".asJsonPrimitive())
370         childNode.set<JsonNode>("ip", "1.2.3.3".asJsonPrimitive())
371         arrayNodeForList3.add(childNode)
372         inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayNodeForList3
373
374         expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayListOf(
375             ExpectedResponseIpAddress(IpAddress("1111", "1.2.3.1")),
376             ExpectedResponseIpAddress(IpAddress("2222", "1.2.3.2")), ExpectedResponseIpAddress(
377                 IpAddress("3333", "1.2.3.3")
378             )
379         ).asJsonType()
380         expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayListOf(
381             IpAddress("1111", "1.2.3.1"),
382             IpAddress("2222", "1.2.3.2"),
383             IpAddress("3333", "1.2.3.3")
384         ).asJsonType()
385     }
386
387     private fun initInputMapAndExpectedValuesForComplexType() {
388         val mapOfComplexType = mutableMapOf<String, JsonNode>()
389         mapOfComplexType["value"] = Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType()
390         mapOfComplexType["port"] = "8888".asJsonType()
391         mapOfComplexType["something"] = "1.2.3.2".asJsonType()
392         inputMapToTestComplexTypeWithOneOutputKeyMapping = mapOfComplexType.asJsonType()
393
394         val objectNode = JacksonUtils.objectMapper.createObjectNode()
395         expectedValueToTestComplexTypeWithOneOutputKeyMapping =
396             objectNode.set("host", Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType())
397
398         val childNode1 = JacksonUtils.objectMapper.createObjectNode()
399         childNode1.set<JsonNode>("name", "my-ipAddress".asJsonPrimitive())
400         childNode1.set<JsonNode>("ipAddress", IpAddress("1111", "1.2.3.1").asJsonType())
401         childNode1.set<JsonNode>("port", "8888".asJsonType())
402         childNode1.set<JsonNode>("something", IpAddress("2222", "1.2.3.1").asJsonType())
403         inputMapToTestComplexTypeWithAllOutputKeyMapping = childNode1
404
405         val childNode2 = JacksonUtils.objectMapper.createObjectNode()
406         childNode2.set<JsonNode>("name", "my-ipAddress".asJsonPrimitive())
407         childNode2.set<JsonNode>("ipAddress", IpAddress("1111", "1.2.3.1").asJsonType())
408         expectedValueToTestComplexTypeWithAllOutputKeyMapping = childNode2
409     }
410
411     private fun prepareResponseNodeForTest(
412         dictionary_source: String,
413         sourceType: String,
414         entrySchema: String,
415         response: Any
416     ): JsonNode {
417
418         resourceAssignment = when (sourceType) {
419             "list" -> {
420                 prepareRADataDictionaryCollection(dictionary_source, sourceType, entrySchema)
421             }
422             "string" -> {
423                 prepareRADataDictionaryOfPrimaryType(dictionary_source)
424             }
425             else -> {
426                 prepareRADataDictionaryComplexType(dictionary_source, sourceType, entrySchema)
427             }
428         }
429
430         val responseNode = checkNotNull(JacksonUtils.getJsonNode(response)) {
431             "Failed to get database query result into Json node."
432         }
433
434         val outputKeyMapping = prepareOutputKeyMapping(dictionary_source)
435
436         return ResourceAssignmentUtils.parseResponseNode(
437             responseNode,
438             resourceAssignment,
439             resourceAssignmentRuntimeService,
440             outputKeyMapping
441         )
442     }
443
444     private fun prepareRADataDictionaryOfPrimaryType(dictionary_source: String): ResourceAssignment {
445         return ResourceAssignment().apply {
446             name = "ipAddress"
447             dictionaryName = "sample-ip"
448             dictionarySource = "$dictionary_source"
449             property = PropertyDefinition().apply {
450                 type = "string"
451             }
452         }
453     }
454
455     private fun prepareRADataDictionaryCollection(
456         dictionary_source: String,
457         sourceType: String,
458         schema: String
459     ): ResourceAssignment {
460         return ResourceAssignment().apply {
461             name = "ipAddress-list"
462             dictionaryName = "sample-licenses"
463             dictionarySource = "$dictionary_source"
464             property = PropertyDefinition().apply {
465                 type = "$sourceType"
466                 entrySchema = EntrySchema().apply {
467                     type = "$schema"
468                 }
469             }
470         }
471     }
472
473     private fun prepareRADataDictionaryComplexType(
474         dictionary_source: String,
475         sourceType: String,
476         schema: String
477     ): ResourceAssignment {
478         return ResourceAssignment().apply {
479             name = "ipAddress-complexType"
480             dictionaryName = "sample-licenses"
481             dictionarySource = "$dictionary_source"
482             property = PropertyDefinition().apply {
483                 type = "$sourceType"
484             }
485         }
486     }
487
488     private fun prepareOutputKeyMapping(dictionary_source: String): MutableMap<String, String> {
489         val outputMapping = mutableMapOf<String, String>()
490
491         when (dictionary_source) {
492             "sample-key-value", "sample-value" -> {
493                 // Primary Type
494                 if (dictionary_source == "sample-key-value")
495                     outputMapping["sample-ip"] = "value"
496             }
497             "listOfString", "mapOfString" -> {
498                 // List of string
499                 outputMapping["ip"] = "value"
500             }
501             "listOfMyDataTypeWithOneOutputKeyMapping", "listOfMyDataTypeWithAllOutputKeyMapping" -> {
502                 // List or map of complex Type
503                 if (dictionary_source == "listOfMyDataTypeWithOneOutputKeyMapping")
504                     outputMapping["ipAddress"] = "value"
505                 else {
506                     outputMapping["port"] = "port"
507                     outputMapping["ip"] = "ip"
508                 }
509             }
510             else -> {
511                 // Complex Type
512                 if (dictionary_source == "complexTypeOneKeys")
513                     outputMapping["host"] = "value"
514                 else {
515                     outputMapping["name"] = "name"
516                     outputMapping["ipAddress"] = "ipAddress"
517                 }
518             }
519         }
520         return outputMapping
521     }
522 }