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