Merge "Add withTrustLevel condition to CmHandle Query API"
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / NetworkCmProxyCmHandleQueryServiceSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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.ncmp.api.impl
22
23 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT
24
25 import org.onap.cps.cpspath.parser.PathParsingException
26 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle
27 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries
28 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueriesImpl
29 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence
30 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters
31 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
32 import org.onap.cps.spi.FetchDescendantsOption
33 import org.onap.cps.spi.exceptions.DataInUseException
34 import org.onap.cps.spi.exceptions.DataValidationException
35 import org.onap.cps.spi.model.ConditionProperties
36 import org.onap.cps.spi.model.DataNode
37 import spock.lang.Specification
38
39 class NetworkCmProxyCmHandleQueryServiceSpec extends Specification {
40
41     def cmHandleQueries = Mock(CmHandleQueries)
42     def partiallyMockedCmHandleQueries = Spy(CmHandleQueries)
43     def mockInventoryPersistence = Mock(InventoryPersistence)
44
45     def dmiRegistry = new DataNode(xpath: NCMP_DMI_REGISTRY_PARENT, childDataNodes: createDataNodeList(['PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4']))
46
47     def objectUnderTest = new NetworkCmProxyCmHandleQueryServiceImpl(cmHandleQueries, mockInventoryPersistence)
48     def objectUnderTestWithPartiallyMockedQueries = new NetworkCmProxyCmHandleQueryServiceImpl(partiallyMockedCmHandleQueries, mockInventoryPersistence)
49
50     def 'Query cm handle ids with cpsPath.'() {
51         given: 'a cmHandleWithCpsPath condition property'
52             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
53             def conditionProperties = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/some/cps/path']])
54             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
55         and: 'the query get the cm handle datanodes excluding all descendants returns a datanode'
56             cmHandleQueries.queryCmHandleAncestorsByCpsPath('/some/cps/path', FetchDescendantsOption.OMIT_DESCENDANTS) >> [new DataNode(leaves: ['id':'some-cmhandle-id'])]
57         when: 'the query is executed for cm handle ids'
58             def result = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
59         then: 'the correct expected cm handles ids are returned'
60             assert result == ['some-cmhandle-id'] as Set
61     }
62
63     def 'Cm handle ids query with error: #scenario.'() {
64         given: 'a cmHandleWithCpsPath condition property'
65             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
66             def conditionProperties = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/some/cps/path']])
67             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
68         and: 'cmHandleQueries throws a path parsing exception'
69             cmHandleQueries.queryCmHandleAncestorsByCpsPath('/some/cps/path', FetchDescendantsOption.OMIT_DESCENDANTS) >> { throw thrownException }
70         when: 'the query is executed for cm handle ids'
71             objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
72         then: 'a data validation exception is thrown'
73             thrown(expectedException)
74         where: 'the following data is used'
75             scenario               | thrownException                                          || expectedException
76             'PathParsingException' | new PathParsingException('some message', 'some details') || DataValidationException
77             'any other Exception'  | new DataInUseException('some message', 'some details')   || DataInUseException
78     }
79
80     def 'Cm handle ids cpsPath query for private properties (not allowed).'() {
81         given: 'a CpsPath condition property for private properties'
82             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
83             def conditionProperties = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/additional-properties']])
84             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
85         when: 'the query is executed for cm handle ids'
86             def result = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
87         then: 'empty result is returned'
88             assert result.isEmpty()
89     }
90
91     def 'Query cm handle ids with module names when #scenario from query.'() {
92         given: 'a modules condition property'
93             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
94             def conditionProperties = createConditionProperties('hasAllModules', [['moduleName': 'some-module-name']])
95             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
96         when: 'the query is executed for cm handle ids'
97             def result = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
98         then: 'the inventory service is called with the correct module names'
99             1 * mockInventoryPersistence.getCmHandleIdsWithGivenModules(['some-module-name']) >> cmHandleIdsFromService
100         and: 'the correct expected cm handles ids are returned'
101             assert result.size() == cmHandleIdsFromService.size()
102             assert result.containsAll(cmHandleIdsFromService)
103         where: 'the following data is used'
104             scenario                  | cmHandleIdsFromService
105             'One anchor returned'     | ['some-cmhandle-id']
106             'No anchors are returned' | []
107     }
108
109     def 'Query cm handles with some trust level query parameters'() {
110         given: 'a trust level condition property'
111             def trustLevelQueryParameters = new CmHandleQueryServiceParameters()
112             def trustLevelConditionProperties = createConditionProperties('cmHandleWithTrustLevel', [['trustLevel': 'COMPLETE'] as Map])
113             trustLevelQueryParameters.setCmHandleQueryParameters([trustLevelConditionProperties])
114         when: 'the query is being executed'
115             objectUnderTest.queryCmHandleIds(trustLevelQueryParameters)
116         then: 'the query is being delegated to the cm handle query service with correct parameter'
117             1 * cmHandleQueries.queryCmHandlesByTrustLevel(['trustLevel': 'COMPLETE'] as Map)
118     }
119
120     def 'Query cm handle details with module names when #scenario from query.'() {
121         given: 'a modules condition property'
122             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
123             def conditionProperties = createConditionProperties('hasAllModules', [['moduleName': 'some-module-name']])
124             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
125         when: 'the query is executed for cm handle ids'
126             def result = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
127         then: 'the inventory service is called with the correct module names'
128             1 * mockInventoryPersistence.getCmHandleIdsWithGivenModules(['some-module-name']) >> ['ch1']
129         and: 'the inventory service is called with teh correct if and returns a yang model cm handle'
130             1 * mockInventoryPersistence.getYangModelCmHandles(['ch1']) >>
131                 [new YangModelCmHandle(id: 'abc', dmiProperties: [new YangModelCmHandle.Property('name','value')], publicProperties: [])]
132         and: 'the expected cm handle(s) are returned as NCMP Service cm handles'
133             assert result[0] instanceof NcmpServiceCmHandle
134             assert result.size() == 1
135             assert result[0].dmiProperties == [name:'value']
136     }
137
138     def 'Query cm handle ids when the query is empty.'() {
139         given: 'We use an empty query'
140             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
141         and: 'the inventory persistence returns the dmi registry datanode with just ids'
142             mockInventoryPersistence.getDataNode(NCMP_DMI_REGISTRY_PARENT, FetchDescendantsOption.DIRECT_CHILDREN_ONLY) >> [dmiRegistry]
143         when: 'the query is executed for both cm handle ids'
144             def result = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
145         then: 'the correct expected cm handles are returned'
146             assert result.containsAll('PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4')
147     }
148
149     def 'Query cm handle details when the query is empty.'() {
150         given: 'We use an empty query'
151             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
152         and: 'the inventory persistence returns the dmi registry datanode with just ids'
153             mockInventoryPersistence.getDataNode(NCMP_DMI_REGISTRY_PARENT) >> [dmiRegistry]
154         when: 'the query is executed for both cm handle details'
155             def result = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
156         then: 'the correct cm handles are returned'
157             assert result.size() == 4
158             assert result.cmHandleId.containsAll('PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4')
159     }
160
161     def 'Query CMHandleId with #scenario.' () {
162         given: 'a query object created with #condition'
163             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
164             def conditionProperties = createConditionProperties(conditionName, [['some-key': 'some-value']])
165             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
166         and: 'the inventoryPersistence returns different CmHandleIds'
167             partiallyMockedCmHandleQueries.queryCmHandlePublicProperties(*_) >> cmHandlesWithMatchingPublicProperties
168             partiallyMockedCmHandleQueries.queryCmHandleAdditionalProperties(*_) >> cmHandlesWithMatchingPrivateProperties
169         when: 'the query executed'
170             def result = objectUnderTestWithPartiallyMockedQueries.queryCmHandleIdsForInventory(cmHandleQueryParameters)
171         then: 'the expected number of results are returned.'
172             assert result.size() == expectedCmHandleIdsSize
173         where: 'the following data is used'
174             scenario                                          | conditionName                | cmHandlesWithMatchingPublicProperties | cmHandlesWithMatchingPrivateProperties || expectedCmHandleIdsSize
175             'all properties, only public matching'            | 'hasAllProperties'           | ['h1', 'h2']                          | null                                   || 2
176             'all properties, no matching cm handles'          | 'hasAllProperties'           | []                                    | []                                     || 0
177             'additional properties, some matching cm handles' | 'hasAllAdditionalProperties' | []                                    | ['h1', 'h2']                           || 2
178             'additional properties, no matching cm handles'   | 'hasAllAdditionalProperties' | null                                  | []                                     || 0
179     }
180
181     def 'Retrieve CMHandleIds by different DMI properties with #scenario.' () {
182         given: 'a query object created with dmi plugin as condition'
183             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
184             def conditionProperties = createConditionProperties('cmHandleWithDmiPlugin', [['some-key': 'some-value']])
185             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
186         and: 'the inventoryPersistence returns different CmHandleIds'
187             partiallyMockedCmHandleQueries.getCmHandleIdsByDmiPluginIdentifier(*_) >> cmHandleQueryResult
188         when: 'the query executed'
189             def result = objectUnderTestWithPartiallyMockedQueries.queryCmHandleIdsForInventory(cmHandleQueryParameters)
190         then: 'the expected number of results are returned.'
191             assert result.size() == expectedCmHandleIdsSize
192         where: 'the following data is used'
193             scenario       | cmHandleQueryResult || expectedCmHandleIdsSize
194             'some matches' | ['h1','h2']         || 2
195             'no matches'   | []                  || 0
196     }
197
198     def 'Combine two query results where #scenario.'() {
199         when: 'two query results in the form of a map of NcmpServiceCmHandles are combined into a single query result'
200             def result = objectUnderTest.combineCmHandleQueryResults(firstQuery, secondQuery)
201         then: 'the returned result is the same as the expected result'
202             result == expectedResult
203         where:
204             scenario                                                     | firstQuery              | secondQuery             || expectedResult
205             'two queries with unique and non unique entries exist'       | ['PNFDemo', 'PNFDemo2'] | ['PNFDemo', 'PNFDemo3'] || ['PNFDemo']
206             'the first query contains entries and second query is empty' | ['PNFDemo', 'PNFDemo2'] | []                      || []
207             'the second query contains entries and first query is empty' | []                      | ['PNFDemo', 'PNFDemo3'] || []
208             'the first query contains entries and second query is null'  | ['PNFDemo', 'PNFDemo2'] | null                    || ['PNFDemo', 'PNFDemo2']
209             'the second query contains entries and first query is null'  | null                    | ['PNFDemo', 'PNFDemo3'] || ['PNFDemo', 'PNFDemo3']
210             'both queries are empty'                                     | []                      | []                      || []
211             'both queries are null'                                      | null                    | null                    || null
212     }
213
214     def createConditionProperties(String conditionName, List<Map<String, String>> conditionParameters) {
215         return new ConditionProperties(conditionName : conditionName, conditionParameters : conditionParameters)
216     }
217
218     def static createDataNodeList(dataNodeIds) {
219         def dataNodes =[]
220         dataNodeIds.each{ dataNodes << new DataNode(xpath: "/dmi-registry/cm-handles[@id='${it}']", leaves: ['id':it]) }
221         return dataNodes
222     }
223 }