Add module name to cps core output
[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.DataMapUtils
26 import org.onap.cps.utils.YangUtils
27 import org.onap.cps.yang.YangTextSchemaSourceSetBuilder
28 import org.opendaylight.yangtools.yang.common.QName
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode
31 import spock.lang.Specification
32
33 class DataNodeBuilderSpec extends Specification {
34
35     Map<String, Map<String, Object>> expectedLeavesByXpathMap = [
36             '/test-tree'                                            : [],
37             '/test-tree/branch[@name=\'Left\']'                     : [name: 'Left'],
38             '/test-tree/branch[@name=\'Left\']/nest'                : [name: 'Small', birds: ['Sparrow', 'Robin', 'Finch']],
39             '/test-tree/branch[@name=\'Right\']'                    : [name: 'Right'],
40             '/test-tree/branch[@name=\'Right\']/nest'               : [name: 'Big', birds: ['Owl', 'Raven', 'Crow']],
41             '/test-tree/fruit[@color=\'Green\' and @name=\'Apple\']': [color: 'Green', name: 'Apple']
42     ]
43
44     String[] networkTopologyModelRfc8345 = [
45             'ietf/ietf-yang-types@2013-07-15.yang',
46             'ietf/ietf-network-topology-state@2018-02-26.yang',
47             'ietf/ietf-network-topology@2018-02-26.yang',
48             'ietf/ietf-network-state@2018-02-26.yang',
49             'ietf/ietf-network@2018-02-26.yang',
50             'ietf/ietf-inet-types@2013-07-15.yang'
51     ]
52
53     def 'Converting NormalizedNode (tree) to a DataNode (tree).'() {
54         given: 'the schema context for expected model'
55             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
56             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
57         and: 'the json data parsed into normalized node object'
58             def jsonData = TestUtils.getResourceFileContent('test-tree.json')
59             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext)
60         when: 'the normalized node is converted to a data node'
61             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).build()
62             def mappedResult = TestUtils.getFlattenMapByXpath(result)
63         then: '5 DataNode objects with unique xpath were created in total'
64             mappedResult.size() == 6
65         and: 'all expected xpaths were built'
66             mappedResult.keySet().containsAll(expectedLeavesByXpathMap.keySet())
67         and: 'each data node contains the expected attributes'
68             mappedResult.each {
69                 xpath, dataNode -> assertLeavesMaps(dataNode.getLeaves(), expectedLeavesByXpathMap[xpath])
70             }
71     }
72
73     def 'Converting NormalizedNode (tree) to a DataNode (tree) for known parent node.'() {
74         given: 'a schema context for expected model'
75             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
76             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
77         and: 'the json data parsed into normalized node object'
78             def jsonData = '{ "branch": [{ "name": "Branch", "nest": { "name": "Nest", "birds": ["bird"] } }] }'
79             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, "/test-tree")
80         when: 'the normalized node is converted to a data node with parent node xpath defined'
81             def result = new DataNodeBuilder()
82                     .withNormalizedNodeTree(normalizedNode)
83                     .withParentNodeXpath("/test-tree")
84                     .build()
85             def mappedResult = TestUtils.getFlattenMapByXpath(result)
86         then: '2 DataNode objects with unique xpath were created in total'
87             mappedResult.size() == 2
88         and: 'all expected xpaths were built'
89             mappedResult.keySet()
90                     .containsAll(['/test-tree/branch[@name=\'Branch\']', '/test-tree/branch[@name=\'Branch\']/nest'])
91     }
92
93     def 'Converting NormalizedNode (tree) to a DataNode (tree) -- augmentation case.'() {
94         given: 'a schema context for expected model'
95             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap(networkTopologyModelRfc8345)
96             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
97         and: 'the json data parsed into normalized node object'
98             def jsonData = TestUtils.getResourceFileContent('ietf/data/ietf-network-topology-sample-rfc8345.json')
99             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext)
100         when: 'the normalized node is converted to a data node '
101             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).build()
102             def mappedResult = TestUtils.getFlattenMapByXpath(result)
103         then: 'all expected data nodes are populated'
104             mappedResult.size() == 32
105             println(mappedResult.keySet().sort())
106         and: 'xpaths for augmentation nodes (link and termination-point nodes) were built correctly'
107             mappedResult.keySet().containsAll([
108                     "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']",
109                     "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-3-1,D3,3-1-1']",
110                     "/networks/network[@network-id='otn-hc']/link[@link-id='D2,2-1-1,D1,1-2-1']",
111                     "/networks/network[@network-id='otn-hc']/link[@link-id='D2,2-3-1,D3,3-2-1']",
112                     "/networks/network[@network-id='otn-hc']/link[@link-id='D3,3-1-1,D1,1-3-1']",
113                     "/networks/network[@network-id='otn-hc']/link[@link-id='D3,3-2-1,D2,2-3-1']",
114                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-0-1']",
115                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-2-1']",
116                     "/networks/network[@network-id='otn-hc']/node[@node-id='D1']/termination-point[@tp-id='1-3-1']",
117                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-0-1']",
118                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-1-1']",
119                     "/networks/network[@network-id='otn-hc']/node[@node-id='D2']/termination-point[@tp-id='2-3-1']",
120                     "/networks/network[@network-id='otn-hc']/node[@node-id='D3']/termination-point[@tp-id='3-1-1']",
121                     "/networks/network[@network-id='otn-hc']/node[@node-id='D3']/termination-point[@tp-id='3-2-1']"
122             ])
123     }
124
125     def 'Converting NormalizedNode (tree) to a DataNode (tree) for known parent node -- augmentation case.'() {
126         given: 'a schema context for expected model'
127             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap(networkTopologyModelRfc8345)
128             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
129         and: 'parent node xpath referencing augmentation node within a model'
130             def parentNodeXpath = "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']"
131         and: 'the json data fragment parsed into normalized node object for given parent node xpath'
132             def jsonData = '{"source": {"source-node": "D1", "source-tp": "1-2-1"}}'
133             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, parentNodeXpath)
134         when: 'the normalized node is converted to a data node with given parent node xpath'
135             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode)
136                     .withParentNodeXpath(parentNodeXpath).build()
137         then: 'the resulting data node represents a child of augmentation node'
138             assert result.xpath == "/networks/network[@network-id='otn-hc']/link[@link-id='D1,1-2-1,D2,2-1-1']/source"
139             assert result.leaves['source-node'] == 'D1'
140             assert result.leaves['source-tp'] == '1-2-1'
141     }
142
143     def 'Converting NormalizedNode into DataNode collection: #scenario.'() {
144         given: 'a schema context for expected model'
145             def yangResourceNameToContent = TestUtils.getYangResourcesAsMap('test-tree.yang')
146             def schemaContext = YangTextSchemaSourceSetBuilder.of(yangResourceNameToContent) getSchemaContext()
147         and: 'parent node xpath referencing parent of list element'
148             def parentNodeXpath = "/test-tree"
149         and: 'the json data fragment (list element) parsed into normalized node object'
150             def normalizedNode = YangUtils.parseJsonData(jsonData, schemaContext, parentNodeXpath)
151         when: 'the normalized node is converted to a data node collection'
152             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode)
153                     .withParentNodeXpath(parentNodeXpath).buildCollection()
154             def resultXpaths = result.collect { it.getXpath() }
155         then: 'the resulting collection contains data nodes for expected list elements'
156             assert resultXpaths.size() == expectedSize
157             assert resultXpaths.containsAll(expectedXpaths)
158         where: 'following parameters are used'
159             scenario           | jsonData                                         | expectedSize | expectedXpaths
160             'single entry'     | '{"branch": [{"name": "One"}]}'                  | 1            | ['/test-tree/branch[@name=\'One\']']
161             'multiple entries' | '{"branch": [{"name": "One"}, {"name": "Two"}]}' | 2            | ['/test-tree/branch[@name=\'One\']', '/test-tree/branch[@name=\'Two\']']
162     }
163
164     def 'Converting NormalizedNode to a DataNode collection -- edge cases: #scenario.'() {
165         when: 'the normalized node is #node'
166             def result = new DataNodeBuilder().withNormalizedNodeTree(normalizedNode).buildCollection()
167         then: 'the resulting collection contains data nodes for expected list elements'
168             assert result.size() == expectedSize
169             assert result.containsAll(expectedNodes)
170         where: 'following parameters are used'
171             scenario                                | node            | normalizedNode       | expectedSize | expectedNodes
172             'NormalizedNode is null'                | 'null'          | null                 | 1            | [ new DataNode() ]
173             'NormalizedNode is an unsupported type' | 'not supported' | Mock(NormalizedNode) | 0            | [ ]
174     }
175
176     def 'Use of adding the module name prefix attribute of data node.'() {
177         when: 'data node is built with a prefix'
178             def testDataNode = new DataNodeBuilder()
179                     .withModuleNamePrefix('sampleModuleNamePrefix')
180                     .withXpath(xPath)
181                     .withLeaves(sampleLeaves)
182                     .build()
183         then: 'the result when node request is a #scenario includes the correct prefix'
184             def result = new DataMapUtils().toDataMapWithIdentifier(testDataNode)
185             result.toString() == expectedResult
186         where: 'the following parameters are used'
187             scenario          | xPath                                       | sampleLeaves                   | expectedResult
188             'list attribute'  | '/test-tree/branch[@name=\'Right\']/nest'   | [name: 'Big', birds: ['Owl']]  | '{sampleModuleNamePrefix:nest={name=Big, birds=[Owl]}}'
189             'container xpath' | '/test-tree/branch[@name=\'Left\']'         | [name: 'Left']                 | '{sampleModuleNamePrefix:branch={name=Left}}'
190     }
191
192     def static assertLeavesMaps(actualLeavesMap, expectedLeavesMap) {
193         expectedLeavesMap.each { key, value ->
194             {
195                 def actualValue = actualLeavesMap[key]
196                 if (value instanceof Collection<?> && actualValue instanceof Collection<?>) {
197                     assert value.size() == actualValue.size()
198                     assert value.containsAll(actualValue)
199                 } else {
200                     assert value == actualValue
201                 }
202             }
203         }
204     }
205 }