Fix sonar code smells
[cps.git] / cps-service / src / test / groovy / org / onap / cps / spi / model / DataNodeBuilderSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Modifications Copyright (C) 2021-2022 Nordix Foundation.
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  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.spi.model
22
23 import org.onap.cps.TestUtils
24 import org.onap.cps.spi.model.DataNodeBuilder
25 import org.onap.cps.utils.YangUtils
26 import org.onap.cps.yang.YangTextSchemaSourceSetBuilder
27 import org.opendaylight.yangtools.yang.common.QName
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode
30 import spock.lang.Specification
31
32 class DataNodeBuilderSpec extends Specification {
33
34     Map<String, Map<String, Object>> expectedLeavesByXpathMap = [
35             '/test-tree'                                            : [],
36             '/test-tree/branch[@name=\'Left\']'                     : [name: 'Left'],
37             '/test-tree/branch[@name=\'Left\']/nest'                : [name: 'Small', birds: ['Sparrow', 'Robin', 'Finch']],
38             '/test-tree/branch[@name=\'Right\']'                    : [name: 'Right'],
39             '/test-tree/branch[@name=\'Right\']/nest'               : [name: 'Big', birds: ['Owl', 'Raven', 'Crow']],
40             '/test-tree/fruit[@color=\'Green\' and @name=\'Apple\']': [color: 'Green', name: 'Apple']
41     ]
42
43     String[] networkTopologyModelRfc8345 = [
44             'ietf/ietf-yang-types@2013-07-15.yang',
45             'ietf/ietf-network-topology-state@2018-02-26.yang',
46             'ietf/ietf-network-topology@2018-02-26.yang',
47             'ietf/ietf-network-state@2018-02-26.yang',
48             'ietf/ietf-network@2018-02-26.yang',
49             'ietf/ietf-inet-types@2013-07-15.yang'
50     ]
51
52     def 'Converting NormalizedNode (tree) to a DataNode (tree).'() {
53         given: 'the schema context for expected model'
54             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
55             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
56         and: 'the json data parsed into normalized node object'
57             def jsonData = TestUtils.getResourceFileContent('test-tree.json')
58             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext)
59         when: 'the normalized node is converted to a data node'
60             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).build()
61             def mappedResult = TestUtils.getFlattenMapByXpath(result)
62         then: '5 DataNode objects with unique xpath were created in total'
63             mappedResult.size() == 6
64         and: 'all expected xpaths were built'
65             mappedResult.keySet().containsAll(expectedLeavesByXpathMap.keySet())
66         and: 'each data node contains the expected attributes'
67             mappedResult.each {
68                 xpath, dataNode -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xpath])
69             }
70     }
71
72     def 'Converting NormalizedNode (tree) to a DataNode (tree) for known parent node.'() {
73         given: 'a schema context for expected model'
74             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
75             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
76         and: 'the json data parsed into normalized node object'
77             def jsonData = '{ "branch": [{ "name": "Branch", "nest": { "name": "Nest", "birds": ["bird"] } }] }'
78             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, "/test-tree")
79         when: 'the normalized node is converted to a data node with parent node xpath defined'
80             def result = new DataNodeBuilder()
81                     .withNormalizedNodeTree(normalizedNode)
82                     .withParentNodeXpath("/test-tree")
83                     .build()
84             def mappedResult = TestUtils.getFlattenMapByXpath(result)
85         then: '2 DataNode objects with unique xpath were created in total'
86             mappedResult.size() == 2
87         and: 'all expected xpaths were built'
88             mappedResult.keySet()
89                     .containsAll(['/test-tree/branch[@name=\'Branch\']', '/test-tree/branch[@name=\'Branch\']/nest'])
90     }
91
92     def 'Converting NormalizedNode (tree) to a DataNode (tree) -- augmentation case.'() {
93         given: 'a schema context for expected model'
94             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap(networkTopologyModelRfc8345)
95             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
96         and: 'the json data parsed into normalized node object'
97             def jsonData = TestUtils.getResourceFileContent('ietf/data/ietf-network-topology-sample-rfc8345.json')
98             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext)
99         when: 'the normalized node is converted to a data node '
100             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).build()
101             def mappedResult = TestUtils.getFlattenMapByXpath(result)
102         then: 'all expected data nodes are populated'
103             mappedResult.size() == 32
104             println(mappedResult.keySet().sort())
105         and: 'xpaths for augmentation nodes (link and termination-point nodes) were built correctly'
106             mappedResult.keySet().containsAll([
107                     "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']",
108                     "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-3-1,D3,3-1-1']",
109                     "/networks/network[@network-id='otn-hc']/link[@link-id='D2,2-1-1,D1,1-2-1']",
110                     "/networks/network[@network-id='otn-hc']/link[@link-id='D2,2-3-1,D3,3-2-1']",
111                     "/networks/network[@network-id='otn-hc']/link[@link-id='D3,3-1-1,D1,1-3-1']",
112                     "/networks/network[@network-id='otn-hc']/link[@link-id='D3,3-2-1,D2,2-3-1']",
113                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-0-1']",
114                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-2-1']",
115                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-3-1']",
116                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-0-1']",
117                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-1-1']",
118                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-3-1']",
119                     "/networks/network[@network-id='otn-hc']/node[@node-id='D3']/termination-point[@tp-id='3-1-1']",
120                     "/networks/network[@network-id='otn-hc']/node[@node-id='D3']/termination-point[@tp-id='3-2-1']"
121             ])
122     }
123
124     def 'Converting NormalizedNode (tree) to a DataNode (tree) for known parent node -- augmentation case.'() {
125         given: 'a schema context for expected model'
126             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap(networkTopologyModelRfc8345)
127             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
128         and: 'parent node xpath referencing augmentation node within a model'
129             def parentNodeXpath = "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']"
130         and: 'the json data fragment parsed into normalized node object for given parent node xpath'
131             def jsonData = '{"source": {"source-node": "D1", "source-tp": "1-2-1"}}'
132             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, parentNodeXpath)
133         when: 'the normalized node is converted to a data node with given parent node xpath'
134             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode)
135                     .withParentNodeXpath(parentNodeXpath).build()
136         then: 'the resulting data node represents a child of augmentation node'
137             assert result.xpath == "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']/source"
138             assert result.leaves['source-node'] == 'D1'
139             assert result.leaves['source-tp'] == '1-2-1'
140     }
141
142     def 'Converting NormalizedNode into DataNode collection: #scenario.'() {
143         given: 'a schema context for expected model'
144             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
145             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
146         and: 'parent node xpath referencing parent of list element'
147             def parentNodeXpath = "/test-tree"
148         and: 'the json data fragment (list element) parsed into normalized node object'
149             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, parentNodeXpath)
150         when: 'the normalized node is converted to a data node collection'
151             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode)
152                     .withParentNodeXpath(parentNodeXpath).buildCollection()
153             def resultXpaths = result.collect { it.getXpath() }
154         then: 'the resulting collection contains data nodes for expected list elements'
155             assert resultXpaths.size() == expectedSize
156             assert resultXpaths.containsAll(expectedXpaths)
157         where: 'following parameters are used'
158             scenario           | jsonData                                         | expectedSize | expectedXpaths
159             'single entry'     | '{"branch": [{"name": "One"}]}'                  | 1            | ['/test-tree/branch[@name=\'One\']']
160             'multiple entries' | '{"branch": [{"name": "One"}, {"name": "Two"}]}' | 2            | ['/test-tree/branch[@name=\'One\']', '/test-tree/branch[@name=\'Two\']']
161     }
162
163     def 'Converting NormalizedNode to a DataNode collection -- edge cases: #scenario.'() {
164         when: 'the normalized node is #node'
165             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).buildCollection()
166         then: 'the resulting collection contains data nodes for expected list elements'
167             assert result.size() == expectedSize
168             assert result.containsAll(expectedNodes)
169         where: 'following parameters are used'
170             scenario                                | node            | normalizedNode       | expectedSize | expectedNodes
171             'NormalizedNode is null'                | 'null'          | null                 | 1            | [ new DataNode() ]
172             'NormalizedNode is an unsupported type' | 'not supported' | Mock(NormalizedNode) | 0            | [ ]
173     }
174
175     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
176         expectedLeavesMap.each { key, value ->
177             {
178                 def actualValue = actualLeavesMap[key]
179                 if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
180                     assert value.size() == actualValue.size()
181                     assert value.containsAll(actualValue)
182                 } else {
183                     assert value == actualValue
184                 }
185             }
186         }
187     }
188 }