Merge "Removed logging of configuration snapshot as it might leak sensitive data...
[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         resourceDefinition.property = PropertyDefinition().apply {
171             this.description = "pnf-id"
172             this.metadata = mutableMapOf("aai-path" to "//path/in/aai")
173         }
174
175         val result = ResourceAssignmentUtils.generateResolutionSummaryData(
176                 listOf(resourceAssignment), mapOf("pnf-id" to resourceDefinition))
177
178         assertEquals("""
179             {
180                 "resolution-summary":[
181                     {
182                         "name":"pnf-id",
183                         "value":"",
184                         "required":false,
185                         "type":"string",
186                         "key-identifiers":[],
187                         "dictionary-description":"pnf-id",
188                         "dictionary-metadata":[
189                             {"name":"aai-path","value":"//path/in/aai"}
190                         ],
191                         "dictionary-name":"pnf-id",
192                         "dictionary-source":"input",
193                         "request-payload":{"mock":true},
194                         "status":"",
195                         "message":""
196                     }
197                 ]
198             }
199         """.replace("\n|\\s".toRegex(), ""), result)
200     }
201
202     private fun createResourceAssignmentForTest(resourceValue: String?): ResourceAssignment {
203         val valueForTest = if (resourceValue == null) null else TextNode(resourceValue)
204         val resourceAssignmentForTest = ResourceAssignment().apply {
205             name = "pnf-id"
206             dictionaryName = "pnf-id"
207             dictionarySource = "input"
208             property = PropertyDefinition().apply {
209                 type = "string"
210                 value = valueForTest
211             }
212         }
213         return resourceAssignmentForTest
214     }
215
216     @Test
217     fun parseResponseNodeTestForPrimitivesTypes() {
218         var outcome = prepareResponseNodeForTest(
219             "sample-value", "string", "",
220             inputMapToTestPrimitiveTypeWithValue
221         )
222         assertEquals(
223             expectedValueToTestPrimitiveType,
224             outcome,
225             "Unexpected outcome returned for primitive type of simple String"
226         )
227         assertEquals(0, resourceAssignment.keyIdentifiers.size)
228
229         outcome = prepareResponseNodeForTest(
230             "sample-key-value", "string", "",
231             inputMapToTestPrimitiveTypeWithKeyValue
232         )
233         assertEquals(
234             expectedValueToTestPrimitiveType,
235             outcome,
236             "Unexpected outcome returned for primitive type of key-value String"
237         )
238         assertEquals(
239                 expectedValueToTestPrimitiveType,
240                 resourceAssignment.keyIdentifiers[0].value
241         )
242     }
243
244     @Test
245     fun parseResponseNodeTestForCollectionsOfString() {
246         var outcome = prepareResponseNodeForTest(
247             "listOfString", "list",
248             "string", inputMapToTestCollectionOfPrimitiveType
249         )
250         assertEquals(
251             expectedValueToTesCollectionOfPrimitiveType,
252             outcome,
253             "unexpected outcome returned for list of String"
254         )
255
256         val expectedKeyIdentifierValue = JacksonUtils.getJsonNode(outcome.map { it["ip"] })
257         assertEquals(
258                 expectedKeyIdentifierValue,
259                 resourceAssignment.keyIdentifiers[0].value
260         )
261
262         // FIXME("Map is not collection type, It is known complex type")
263         // outcome = prepareResponseNodeForTest(
264         //     "mapOfString", "map", "string",
265         //     inputMapToTestCollectionOfPrimitiveType
266         // )
267         // assertEquals(
268         //     expectedValueToTesCollectionOfPrimitiveType,
269         //     outcome,
270         //     "unexpected outcome returned for map of String"
271         // )
272     }
273
274     @Test
275     fun parseResponseNodeTestForCollectionsOfComplexType() {
276         var outcome = prepareResponseNodeForTest(
277             "listOfMyDataTypeWithOneOutputKeyMapping", "list",
278             "ip-address", inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping
279         )
280         assertEquals(
281             expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping,
282             outcome,
283             "unexpected outcome returned for list of String"
284         )
285
286         outcome = prepareResponseNodeForTest(
287             "listOfMyDataTypeWithAllOutputKeyMapping", "list",
288             "ip-address", inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping
289         )
290         assertEquals(
291             expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping,
292             outcome,
293             "unexpected outcome returned for list of String"
294         )
295     }
296
297     @Test
298     fun `parseResponseNodeTestForComplexType find one output key mapping`() {
299         val outcome = prepareResponseNodeForTest(
300             "complexTypeOneKeys", "host",
301             "", inputMapToTestComplexTypeWithOneOutputKeyMapping
302         )
303         assertEquals(
304             expectedValueToTestComplexTypeWithOneOutputKeyMapping,
305             outcome,
306             "Unexpected outcome returned for complex type"
307         )
308         assertEquals(
309                 expectedValueToTestComplexTypeWithOneOutputKeyMapping["host"],
310                 resourceAssignment.keyIdentifiers[0].value)
311     }
312
313     @Test
314     fun `parseResponseNodeTestForComplexType find all output key mapping`() {
315         val outcome = prepareResponseNodeForTest(
316             "complexTypeAllKeys", "host",
317             "", inputMapToTestComplexTypeWithAllOutputKeyMapping
318         )
319         assertEquals(
320             expectedValueToTestComplexTypeWithAllOutputKeyMapping,
321             outcome,
322             "Unexpected outcome returned for complex type"
323         )
324         assertEquals(2, resourceAssignment.keyIdentifiers.size)
325         assertEquals(
326                 expectedValueToTestComplexTypeWithAllOutputKeyMapping["name"],
327                 resourceAssignment.keyIdentifiers[0].value
328         )
329
330         assertEquals(
331                 expectedValueToTestComplexTypeWithAllOutputKeyMapping["ipAddress"],
332                 resourceAssignment.keyIdentifiers[1].value
333         )
334     }
335
336     private fun initInputMapAndExpectedValuesForPrimitiveType() {
337         inputMapToTestPrimitiveTypeWithValue = "1.2.3.1".asJsonType()
338         val keyValue = mutableMapOf<String, String>()
339         keyValue["value"] = "1.2.3.1"
340         inputMapToTestPrimitiveTypeWithKeyValue = keyValue.asJsonType()
341         expectedValueToTestPrimitiveType = TextNode("1.2.3.1")
342     }
343
344     private fun initInputMapAndExpectedValuesForCollection() {
345         val listOfIps = arrayListOf("1.2.3.1", "1.2.3.2", "1.2.3.3")
346         val arrayNodeForList1 = JacksonUtils.objectMapper.createArrayNode()
347         listOfIps.forEach {
348             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
349             arrayChildNode.set<JsonNode>("value", it.asJsonPrimitive())
350             arrayNodeForList1.add(arrayChildNode)
351         }
352         inputMapToTestCollectionOfPrimitiveType = arrayNodeForList1
353
354         expectedValueToTesCollectionOfPrimitiveType = arrayListOf(
355             ExpectedResponseIp("1.2.3.1"),
356             ExpectedResponseIp("1.2.3.2"), ExpectedResponseIp("1.2.3.3")
357         ).asJsonType()
358
359         val listOfIpAddresses = arrayListOf(
360             IpAddress("1111", "1.2.3.1").asJsonType(),
361             IpAddress("2222", "1.2.3.2").asJsonType(), IpAddress("3333", "1.2.3.3").asJsonType()
362         )
363         val arrayNodeForList2 = JacksonUtils.objectMapper.createArrayNode()
364         listOfIpAddresses.forEach {
365             val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()
366             arrayChildNode.set<JsonNode>("value", it.asJsonType())
367             arrayNodeForList2.add(arrayChildNode)
368         }
369         inputMapToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayNodeForList2
370
371         val arrayNodeForList3 = JacksonUtils.objectMapper.createArrayNode()
372         var childNode = JacksonUtils.objectMapper.createObjectNode()
373         childNode.set<JsonNode>("port", "1111".asJsonPrimitive())
374         childNode.set<JsonNode>("ip", "1.2.3.1".asJsonPrimitive())
375         arrayNodeForList3.add(childNode)
376         childNode = JacksonUtils.objectMapper.createObjectNode()
377         childNode.set<JsonNode>("port", "2222".asJsonPrimitive())
378         childNode.set<JsonNode>("ip", "1.2.3.2".asJsonPrimitive())
379         arrayNodeForList3.add(childNode)
380         childNode = JacksonUtils.objectMapper.createObjectNode()
381         childNode.set<JsonNode>("port", "3333".asJsonPrimitive())
382         childNode.set<JsonNode>("ip", "1.2.3.3".asJsonPrimitive())
383         arrayNodeForList3.add(childNode)
384         inputMapToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayNodeForList3
385
386         expectedValueToTestCollectionOfComplexTypeWithOneOutputKeyMapping = arrayListOf(
387             ExpectedResponseIpAddress(IpAddress("1111", "1.2.3.1")),
388             ExpectedResponseIpAddress(IpAddress("2222", "1.2.3.2")), ExpectedResponseIpAddress(
389                 IpAddress("3333", "1.2.3.3")
390             )
391         ).asJsonType()
392         expectedValueToTestCollectionOfComplexTypeWithAllOutputKeyMapping = arrayListOf(
393             IpAddress("1111", "1.2.3.1"),
394             IpAddress("2222", "1.2.3.2"),
395             IpAddress("3333", "1.2.3.3")
396         ).asJsonType()
397     }
398
399     private fun initInputMapAndExpectedValuesForComplexType() {
400         val mapOfComplexType = mutableMapOf<String, JsonNode>()
401         mapOfComplexType["value"] = Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType()
402         mapOfComplexType["port"] = "8888".asJsonType()
403         mapOfComplexType["something"] = "1.2.3.2".asJsonType()
404         inputMapToTestComplexTypeWithOneOutputKeyMapping = mapOfComplexType.asJsonType()
405
406         val objectNode = JacksonUtils.objectMapper.createObjectNode()
407         expectedValueToTestComplexTypeWithOneOutputKeyMapping =
408             objectNode.set("host", Host("my-ipAddress", IpAddress("1111", "1.2.3.1")).asJsonType())
409
410         val childNode1 = JacksonUtils.objectMapper.createObjectNode()
411         childNode1.set<JsonNode>("name", "my-ipAddress".asJsonPrimitive())
412         childNode1.set<JsonNode>("ipAddress", IpAddress("1111", "1.2.3.1").asJsonType())
413         childNode1.set<JsonNode>("port", "8888".asJsonType())
414         childNode1.set<JsonNode>("something", IpAddress("2222", "1.2.3.1").asJsonType())
415         inputMapToTestComplexTypeWithAllOutputKeyMapping = childNode1
416
417         val childNode2 = JacksonUtils.objectMapper.createObjectNode()
418         childNode2.set<JsonNode>("name", "my-ipAddress".asJsonPrimitive())
419         childNode2.set<JsonNode>("ipAddress", IpAddress("1111", "1.2.3.1").asJsonType())
420         expectedValueToTestComplexTypeWithAllOutputKeyMapping = childNode2
421     }
422
423     private fun prepareResponseNodeForTest(
424         dictionary_source: String,
425         sourceType: String,
426         entrySchema: String,
427         response: Any
428     ): JsonNode {
429
430         resourceAssignment = when (sourceType) {
431             "list" -> {
432                 prepareRADataDictionaryCollection(dictionary_source, sourceType, entrySchema)
433             }
434             "string" -> {
435                 prepareRADataDictionaryOfPrimaryType(dictionary_source)
436             }
437             else -> {
438                 prepareRADataDictionaryComplexType(dictionary_source, sourceType, entrySchema)
439             }
440         }
441
442         val responseNode = checkNotNull(JacksonUtils.getJsonNode(response)) {
443             "Failed to get database query result into Json node."
444         }
445
446         val outputKeyMapping = prepareOutputKeyMapping(dictionary_source)
447
448         return ResourceAssignmentUtils.parseResponseNode(
449             responseNode,
450             resourceAssignment,
451             resourceAssignmentRuntimeService,
452             outputKeyMapping
453         )
454     }
455
456     private fun prepareRADataDictionaryOfPrimaryType(dictionary_source: String): ResourceAssignment {
457         return ResourceAssignment().apply {
458             name = "ipAddress"
459             dictionaryName = "sample-ip"
460             dictionarySource = "$dictionary_source"
461             property = PropertyDefinition().apply {
462                 type = "string"
463             }
464         }
465     }
466
467     private fun prepareRADataDictionaryCollection(
468         dictionary_source: String,
469         sourceType: String,
470         schema: String
471     ): ResourceAssignment {
472         return ResourceAssignment().apply {
473             name = "ipAddress-list"
474             dictionaryName = "sample-licenses"
475             dictionarySource = "$dictionary_source"
476             property = PropertyDefinition().apply {
477                 type = "$sourceType"
478                 entrySchema = EntrySchema().apply {
479                     type = "$schema"
480                 }
481             }
482         }
483     }
484
485     private fun prepareRADataDictionaryComplexType(
486         dictionary_source: String,
487         sourceType: String,
488         schema: String
489     ): ResourceAssignment {
490         return ResourceAssignment().apply {
491             name = "ipAddress-complexType"
492             dictionaryName = "sample-licenses"
493             dictionarySource = "$dictionary_source"
494             property = PropertyDefinition().apply {
495                 type = "$sourceType"
496             }
497         }
498     }
499
500     private fun prepareOutputKeyMapping(dictionary_source: String): MutableMap<String, String> {
501         val outputMapping = mutableMapOf<String, String>()
502
503         when (dictionary_source) {
504             "sample-key-value", "sample-value" -> {
505                 // Primary Type
506                 if (dictionary_source == "sample-key-value")
507                     outputMapping["sample-ip"] = "value"
508             }
509             "listOfString", "mapOfString" -> {
510                 // List of string
511                 outputMapping["ip"] = "value"
512             }
513             "listOfMyDataTypeWithOneOutputKeyMapping", "listOfMyDataTypeWithAllOutputKeyMapping" -> {
514                 // List or map of complex Type
515                 if (dictionary_source == "listOfMyDataTypeWithOneOutputKeyMapping")
516                     outputMapping["ipAddress"] = "value"
517                 else {
518                     outputMapping["port"] = "port"
519                     outputMapping["ip"] = "ip"
520                 }
521             }
522             else -> {
523                 // Complex Type
524                 if (dictionary_source == "complexTypeOneKeys")
525                     outputMapping["host"] = "value"
526                 else {
527                     outputMapping["name"] = "name"
528                     outputMapping["ipAddress"] = "ipAddress"
529                 }
530             }
531         }
532         return outputMapping
533     }
534 }